1

我正在开发一个 ASP.Net VB Web 应用程序

该应用程序包含一个GridView显示我创建的数据表中的用户表的记录。该数据库是一个Sql server 数据库。

下面的代码将数据插入到一个表中,并通过内置函数从表@@Identity中插入最近添加的记录 id( tt_id),trainingTbl并将该记录 id 插入到userAssessmentTbl. 将身份添加到第二个userAssessmentTbl表可以正常工作。

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim lblUsr2 As Control = FindControlRecursive(MultiTabs, "txtUsr")
        Dim strQuery As String
        Dim cmd As SqlCommand

        strQuery = "Insert into trainingTbl(s_id, t_date, EditorId, wa_id, st_id) values(@s_id , @t_date, @EditorId, @wa_id, @st_id  ) Insert into userAssessmentTbl(tt_id, UserId) values(@@Identity, @UserId)"

        cmd = New SqlCommand(strQuery)

        cmd.Parameters.AddWithValue("@s_id", DDLCourse.Text)
        cmd.Parameters.AddWithValue("@t_date", Convert.ToDateTime(txtDate.Text))
        cmd.Parameters.AddWithValue("@EditorId", User.Identity.Name.ToString())
        cmd.Parameters.AddWithValue("@st_id", myLblStation.Value().ToString)
        cmd.Parameters.AddWithValue("@wa_id", myLblWatch.Value().ToString)
        cmd.Parameters.AddWithValue("@UserId", lblUsr2.UniqueID.ToString)
        InsertUpdateData(cmd)
    End Sub

我遇到的问题似乎集中在如何将 a uniqueidenifierfrom aGridView插入userAssessmentTbl数据库!

以及如何,我想使用循环我可以将该 Gridview ( GridView1)中的 UserId 记录userAssessmentTbl与来自@@Identity.

这部分插入参数似乎不正确:

cmd.Parameters.AddWithValue("@UserId", lblUsr2.UniqueID().ToString)

我遇到的错误是:'从字符串转换为唯一标识符时转换失败。'

我也试过这样:

cmd.Parameters.AddWithValue("@UserId", SqlDbType.UniqueIdentifier).Value().ToString()

我遇到了错误:'操作数类型冲突:int 与 uniqueidentifier 不兼容'

问题已略微更改为如何将字符串插入到 DataType 为 Uniqueidentifier 的 SQL DB 中?

任何帮助将不胜感激。

4

1 回答 1

1

Well first of all:

@@IDENTITY returns the most recently created identity for your current connection, not necessarily the identity for the recently added row in a table. Always use SCOPE_IDENTITY() to return the identity of the recently added row.


Secondly, to asnwer your question:

The SQL type Uniqueidentifier and the CLR type Guid match up.

So instead of passing "@UserId" in as a parameter you need to create a Guid out of the string value.

Dim userID As Guid = New Guid(lblUsr2.UniqueID.ToString)
于 2012-06-24T17:08:43.970 回答