Error in VB.Net. Conversion error when converting from character string to uniqueidentifier

I get "Conversion error when converting from character string to uniqueidentifier".

I use String on the VB side and GUID on the database side .....

Is there an equivalent field that I can use on the VB side that can work well with the "uniqueidentifier" data type on the Sql server

+4
source share
1 answer

If you already have your value as a string, and since you are writing your SQL manually, you can CONVERTdo it like this:

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))

EDIT: , Guid, :

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

parmList.Add(String.Empty)

NULL GUID, :

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 Injection, . , , uniqueidentifier.

+1

All Articles