如果您已经将值作为字符串,并且由于您是手动编写 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。