VB 操作sqlserver执行insert into语句,如何返回自增的ID值?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了VB 操作sqlserver执行insert into语句,如何返回自增的ID值?相关的知识,希望对你有一定的参考价值。

看来还是要我自己回答了

sql = "insert into DBname (Name) values ('张三')"
cn.execute(sql)
sql = "Select @@identity as id"
rs.open sql
GteId = rs.fields("id").value

参考技术A DECLARE @ID nvarchar(20)
SELECT @ID=inserted.id FROM inserted

在 VB.NET 中从 SQL Server 执行存储过程?

【中文标题】在 VB.NET 中从 SQL Server 执行存储过程?【英文标题】:Executing a Stored Procedure from SQL Server in VB.NET? 【发布时间】:2014-04-14 07:48:30 【问题描述】:

如何通过 VB.NET 在 SQL Server 中执行存储过程?

对于我通常使用的普通 SQL 命令:

Command = New SQLCommand("Select * From Table Where Column ='Value' ",Connection)
Command.ExecuteNonQuery '( Or scalar depending ). 

是不是一样但是你选择了存储过程?

【问题讨论】:

Execute a SQL Stored Procedure and process the results的可能重复 【参考方案1】:
Dim Command As New SQLCommand("usp_MyStoredProc", connection)
Command.CommandType = CommandType.StoredProcedure
Command.ExecuteNonQuery()

【讨论】:

【参考方案2】:

在 .vb 文件的顶部:

Imports System.data.sqlclient

在您的代码中:

'Setup SQL Command'
Dim CMD as new sqlCommand("StoredProcedureName")
CMD.parameters("@Parameter1", sqlDBType.Int).value = Param_1_value

Dim connection As New SqlConnection(connectionString)
CMD.Connection = connection
CMD.CommandType = CommandType.StoredProcedure

Dim adapter As New SqlDataAdapter(CMD)
adapter.SelectCommand.CommandTimeout = 300

'Fill the dataset'
 Dim DS as DataSet    
 adapter.Fill(ds)
 connection.Close()   

 'Now, read through your data:'
 For Each DR as DataRow in DS.Tables(0).rows
  Msgbox("The value in Column ""ColumnName1"": " & cstr(DR("ColumnName1")))
 next

现在基本的东西都没有了,

我强烈建议将实际的 SqlCommand 执行抽象为一个函数。

这是我在各种项目中以某种形式使用的通用函数:

    ''' <summary>Executes a SqlCommand on the Main DB Connection. Usage: Dim ds As DataSet = ExecuteCMD(CMD)</summary>'''
    ''' <param name="CMD">The command type will be determined based upon whether or not the commandText has a space in it. If it has a space, it is a Text command ("select ... from .."),''' 
    ''' otherwise if there is just one token, it's a stored procedure command</param>''''
    Function ExecuteCMD(ByRef CMD As SqlCommand) As DataSet
        Dim connectionString As String = ConfigurationManager.ConnectionStrings("main").ConnectionString
        Dim ds As New DataSet()

        Try
            Dim connection As New SqlConnection(connectionString)
            CMD.Connection = connection

            'Assume that it's a stored procedure command type if there is no space in the command text. Example: "sp_Select_Customer" vs. "select * from Customers"
            If CMD.CommandText.Contains(" ") Then
                CMD.CommandType = CommandType.Text
            Else
                CMD.CommandType = CommandType.StoredProcedure
            End If

            Dim adapter As New SqlDataAdapter(CMD)
            adapter.SelectCommand.CommandTimeout = 300

            'fill the dataset'
            adapter.Fill(ds)
            connection.Close()

        Catch ex As Exception
            ' The connection failed. Display an error message.'
            Throw New Exception("Database Error: " & ex.Message)
        End Try

        Return ds
    End Function

你有,你的SQL执行+阅读代码非常简单:

 '----------------------------------------------------------------------'
 Dim CMD As New SqlCommand("GetProductName")
 CMD.Parameters.Add("@productID", SqlDbType.Int).Value = ProductID
 Dim DR As DataRow = ExecuteCMD(CMD).Tables(0).Rows(0)
 MsgBox("Product Name: " & cstr(DR(0)))
 '----------------------------------------------------------------------'

SOURCE

【讨论】:

以上是关于VB 操作sqlserver执行insert into语句,如何返回自增的ID值?的主要内容,如果未能解决你的问题,请参考以下文章

简单的sqlserver批量插入数据easy batch insert data in sqlserver

sqlserver中set IDENTITY_INSERT on 和 off 的设置方法

使用SQLServer2005插入一条数据时返回当前插入数据的ID

VB语言使用ADO连接操作SQLServer数据库教程

JAVA使用JDBC技术操作SqlServer数据库执行存储过程

VB.NET关于datagirdview的数据通过按钮更新到sqlserver,要求代码例子