VB.Net中的错误 - 从字符串转换为uniqueidentifier时转换失败

时间:2013-10-31 14:47:23

标签: sql-server vb.net datatable uniqueidentifier

我得到了一个"从字符串转换为uniqueidentifier时转换失败。"

我在VB端使用String,在数据库端使用GUID .....

是否存在我可以在VB端使用的等效字段,该字段可以与" uniqueidentifier" Sql Server中的数据类型

1 个答案:

答案 0 :(得分:1)

如果您已将值作为字符串,并且由于您手动编写SQL,则可以CONVERT这样:

strSql.Append("INSERT INTO tableName ")
strSql.Append("(GUID, ParentObsSetGUID, ChildObsSetGUID, ChildObsItemGUID) ")
strSql.Append(String.Format("VALUES (CONVERT(uniqueidentifier, '{0}'), CONVERT(uniqueidentifier, '{1}'), CONVERT(uniqueidentifier, '{2}'), CONVERT(uniqueidentifier, '{3}'))", parmList.ToArray))

编辑:如果你有一个空字符串而你需要一个新的Guid,那就这样做:

parmList.Add(Guid.NewGuid().ToString())

而不是

parmList.Add(String.Empty)

如果您希望在GUID列中插入NULL,则需要将代码的最后一位更改为:

parmList.Add(dtNewGUID.Rows(0).Item(0).ToString)
parmList.Add(dtResultParentGUID.Rows(0).Item(0).ToString)
parmList.Add(dtResultChildGUID.Rows(0).Item(0).ToString)
// remove the line with the empty string parameter
strSql.Append("INSERT INTO tableName ")
strSql.Append("(GUID, ParentObsSetGUID, ChildObsSetGUID, ChildObsItemGUID) ")
strSql.Append(String.Format("VALUES (CONVERT(uniqueidentifier, '{0}'), CONVERT(uniqueidentifier, '{1}'),
CONVERT(uniqueidentifier, '{2}'), NULL)", parmList.ToArray))
// Note the change to the last line. '{3}' becomes NULL.
// Make sure you remove the single quotes

注意:您的代码(以及此答案)易受SQL注入攻击,但这是另一回事。至少在这个答案中你知道如何将字符串转换为uniqueidentifier

相关问题