无需存储过程即可在ADO.Net中获取输出值

时间:2014-04-11 09:06:22

标签: sql-server vb.net ado.net adodb

我正在将ADODB应用程序转换为ADO.Net,并在其中包含一个插入新行并返回自动增量值的命令,如下所示: -

INSERT INTO [MyDB].[dbo].[MyTable] (COLUMN1, COLUMN2) OUTPUT inserted.ID_PRIMARY
                      VALUES ('This', 'That')

然后可以获取OUTPUT值并离开。但是当我尝试使用ADO.Net时,就像这样: -

command_string = (as above)
Dim insert_command   As SqlCommand     = New SqlCommand(command_string, database_connection)
Dim output_parameter As SqlParameter   = New SqlParameter("@inserted.ID_PRIMARY", SqlDbType.Int)
Dim transaction      As SqlTransaction = database_connection.BeginTransaction(System.Data.IsolationLevel.Serializable)
insert_command.Transaction = transaction
output_parameter.Direction = ParameterDirection.Output
insert_command.Parameters.Add(output_parameter)
insert_command.ExecuteNonQuery()
transaction.Commit

返回错误: -

  

SqlException(0x80131904)'。'

附近的语法不正确

我很欣赏我可以使用存储过程来执行插入并检索返回值,如here所述,但我想知道是否有任何方法可以在没有存储过程的情况下完成?还是我忽略了一些微不足道的错误?

4 个答案:

答案 0 :(得分:1)

ID中新插入的OUTPUT Inserted.ID_PRIMARY将是从语句返回的数据集。您需要使用ExecuteReader方法来读取返回的值:

' setup as above - except you don't need the "output_parameter"
Dim reader As SqlDataReader = insert_command.ExecuteReader()

While reader.Read()
    ' get your newly inserted ID's here as returned dataset
    Dim newlyInsertedID As Integer = reader.GetInt32(0)

    ' if you insert multiple rows at once, you might need store those ID's 
    ' that you fetch back one by one into a list or something
End While

答案 1 :(得分:1)

您可以利用以下事实:使用SQL Server,您可以在一个批处理中发出两个sql命令。并使用T-SQL函数SELECT SCOPE_IDENTITY查找添加到当前范围的最新标识值

Dim sqlText = "INSERT INTO [MyDB].[dbo].[MyTable] (COLUMN1, COLUMN2) " & _
              "VALUES ('This', 'That'); SELECT SCOPE_IDENTITY()"
Dim insert_command = New SqlCommand(sqlText, database_connection)
insert_command.Transaction = transaction
Dim result = Convert.ToInt32(insert_command.ExecuteScalar())
transaction.Commit

否则,如果要使用语法,请删除输出参数

Dim sqlText = "INSERT INTO [MyDB].[dbo].[MyTable] (COLUMN1, COLUMN2) " & _ 
              "OUTPUT inserted.ID_PRIMARY  VALUES ('This', 'That')"
Dim insert_command  = New SqlCommand(sqlText, database_connection)
insert_command.Transaction = transaction
Dim result = Convert.ToInt32(insert_command.ExecuteScalar())
transaction.Commit

但和以前一样,使用ExecuteScalar来检索查询返回的第一行/第一列的值

答案 2 :(得分:1)

通过将SQL更改为: -

来更正语法错误
INSERT INTO [MyDB].[dbo].[MyTable] (COLUMN1, COLUMN2)
    OUTPUT inserted.ID_PRIMARY As ID_PRIMARY
        VALUES ('This', 'That')

并设置如下参数: -

Dim output_parameter As SqlParameter = New SqlParameter("@ID_PRIMARY", SqlDbType.Int)

答案 3 :(得分:1)

请尝试以下代码:

/****** Object:  Table [dbo].[Pedidos]    Script Date: 03/01/2015 16:48:17 ******/
SET ANSI_NULLS ON
GO


SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[Pedidos](
[PedidoID] [int] IDENTITY(1,1) NOT NULL,
[Data] [date] NOT NULL,
[clienteID] [int] NOT NULL,
 CONSTRAINT [PK_Pedidos] PRIMARY KEY CLUSTERED 
(
[PedidoID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY =     OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

ALTER TABLE [dbo].[Pedidos]  WITH CHECK ADD  CONSTRAINT     [FK_Pedidos_Clientes] FOREIGN KEY([clienteID])
REFERENCES [dbo].[Clientes] ([clienteID])
GO

ALTER TABLE [dbo].[Pedidos] CHECK CONSTRAINT [FK_Pedidos_Clientes]
GO

使用Dim Identity As Integer或声明PUBLIC 返回插入的标识记录自动增量字段PedidoID的值。

    Dim connection As SqlConnection = databaseDB.GetConnection
    Dim insertStatement As String _
        = "INSERT [dbo].[Pedidos] " _
        & "([Data], [clienteID]) " _
        & "VALUES (@Data, @clienteID) SELECT @PedidoID = SCOPE_IDENTITY()" 'SELECT SCOPE_IDENTITY() AS 'Identity
    Dim insertCommand As New SqlCommand(insertStatement, connection)
    insertCommand.CommandType = CommandType.Text
    insertCommand.Parameters.AddWithValue("@Data", dbo_pedidos.Data)
    insertCommand.Parameters.AddWithValue("@clienteID", dbo_pedidos.clienteID)
    ' Inclui o SqlParameter para retornar o novo valor identity
    ' Define o ParameterDirection como Output.(Saida)
    insertCommand.Parameters.Add("@PedidoID", SqlDbType.Int, 0, "PedidoID")
    insertCommand.Parameters("@PedidoID").Direction = ParameterDirection.Output

    Try
        connection.Open()
        Dim count As Integer = insertCommand.ExecuteNonQuery()
        If count > 0 Then
            Identity = insertCommand.Parameters("@PedidoID").Value
            Return True
        Else
            Return False
        End If
    Catch ex As SqlException
        Throw ex
    Finally
        connection.Close()
    End Try