3

I have a system that has been running on Windows Server 2003 and SQL Server 2000 for a number of years without a problem. Recently I moved the system to Windows Server 2008 R2 and SQL Server 2008 R2 and have started get a very strange intermittent problems.

I am inserting a row into a table with an identity column and executing a select to retrieve the identity value. Most of the time this code works fine but at random intervals the identity isn't returned. Sometimes no row is found so dr.Read returns false, other times I get a row back but there is no identity column in it. I checked the database and the insert has succeeded, it's just that the identity isn't returned. There are no triggers on the table.

I also tried changing the SQL to:

INSERT INTO test (value) 
VALUES (100) 
SELECT SCOPE_IDENTITY() AS 'identity' OPTION (MAXDOP 1) 

in case I was running into the 'max degree of parallelism' bug but that didn't help either.

Here is relevant code (slightly simplified for illustration):

Dim dr As SqlDataReader = Nothing
Dim objCommand As New SqlCommand
Dim oConn As New SqlConnection
Dim id as integer

oConn.ConnectionString = connStr 
oConn.open()

objCommand = New SqlCommand("INSERT INTO test (value) VALUES (100) SELECT SCOPE_IDENTITY() AS 'identity'", oConn, tr)

try
    dr = objCommand.ExecuteReader
    If Not dr.Read Then
        Throw (New Exception("Could not read IDENTITY"))
    Else
        id = dr("identity")
    End If
Catch
    Throw
Finally            
    If Not dr Is Nothing Then dr.Close()
    oConn.close()
End Try
4

2 回答 2

0

如果您只是将它们作为两个单独的语句执行会怎样?

objCommand = New SqlCommand("INSERT INTO test (value) VALUES (100); SELECT SCOPE_IDENTITY() AS 'identity'", oConn, tr)

SCOPE_IDENTITY为您提供“插入到同一范围内的标识列中的最后一个标识值”。

于 2012-10-24T16:27:45.410 回答
0

SQL Server 2008 R2 上的另一个选项是使用该OUTPUT子句

INSERT INTO test (value) 
OUTPUT INSERTED.ID
VALUES (100) 

这将输出ID插入的行的 - 这就是您想要的标识值。

ID从您的代码中,如果您使用ExecuteScalar(而不是) ,您应该能够获取它,ExecuteReader并且只需将object您返回的类型转换为int

于 2012-10-24T16:56:53.620 回答