下面将为您介绍通过程序获得SQL Server自增型字段的函数--GetKey函数的方法,供您参考,希望对你更好学习SQL中函数能够有所帮助。
概述:
通过程序来产生自增型字段,可以避免多用户操作的读取脏数据,操作也很简便.可以更好的在程序中控制这些关键字段的数值.
关键步骤:
1. 创建用于存放需要自增的数据表.(systemkey)
SQL Script 如下:
- if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SystemKey]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
- drop table [dbo].[SystemKey]
- GO
- CREATE TABLE [dbo].[SystemKey] (
- [ID] [int] NOT NULL ,
- [KeyName] [nvarchar] (50) NOT NULL ,
- [KeyValue] [int] NOT NULL ,
- [SourceID] [nvarchar] (50) NOT NULL ,
- [LockTime] [datetime] NULL
- ) ON [PRIMARY]
- GO
KeyName:关键字的字段名(我们需要的字段名称,手工添加到这个表中)
KeyValue:对应字段名的值.
SourceID:字段的来源,如果没有可以填””
LockTime:锁定的时间,在程序内部使用.
2. GetKeys函数方程,通过调用GetKeys函数得到关键字的值.
函数描述如下:
- Imports Microsoft.ApplicationBlocks.Data
- Imports Microsoft.VisualBasic.CompilerServices
- Imports System.Threading
- Imports System.Data.SqlClient
- Public Class ClassTestClass ClassTest
- Public Function GetKeys()Function GetKeys(ByVal KeyName As String, ByVal Source As String, ByVal CNString As String) As Integer
- Dim connection As New SqlConnection(CNString)
- Dim NewNum As Integer
- Dim obj2 As Object
- Dim sFlage As String = "Flag"
- Try
- Dim sql As String
- Dim time As DateTime = DateAndTime.Now.AddSeconds(1)
- connection.Open()
- Do While (StringType.StrCmp(sFlage, "", False) <> 0)
- sql = (("Update [SystemKey] Set [SourceID]='" & Source & "', [LockTime]=GetDate() Where [KeyName]='" & KeyName) & "' AND ((DATEADD(millisecond, 1000, LockTime)
- Dim j As Integer = SqlHelper.ExecuteNonQuery(connection, CommandType.Text, sql)
- If (j > 0) Then
- sFlage = ""
- Exit Do
- End If
- sFlage = "Err"
- connection.Close()
- If (DateTime.Compare(time, DateAndTime.Now) < 0) Then
- Return -1
- End If
- Thread.Sleep(10)
- Loop
- sql = "Select KeyValue From [SystemKey] Where [KeyName]='" & KeyName & "' AND SourceID='" & Source & "'"
- Dim OldNum As Object = SqlHelper.ExecuteScalar(connection, CommandType.Text, sql)
- Dim num As Integer = (IntegerType.FromObject(OldNum) + 1)
- sql = "Update [SystemKey] Set [KeyValue]=" & StringType.FromInteger(num) & ", [SourceID]='' Where [KeyName]='" & KeyName & "'"
- SqlHelper.ExecuteNonQuery(connection, CommandType.Text, sql)
- NewNum = num
- Catch exception As Exception
- NewNum = -1
- Finally
- If Not connection Is Nothing Then
- CType(connection, IDisposable).Dispose()
- End If
- End Try
- Return NewNum
- End Function
- End Class
【编辑推荐】
SQL中DATENAME函数的用法
SQL中循环语句的效果实例
SQL中类似For循环处理的实例
对存储过程代替SQL语句的讨论
SQL聚合函数之Avg 函数
本文题目:通过程序获得SQL数据库中的GetKey函数
文章来源:http://www.mswzjz.cn/qtweb/news44/344894.html
攀枝花网站建设、攀枝花网站运维推广公司-贝锐智能,是专注品牌与效果的网络营销公司;服务项目有等
声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 贝锐智能