I have a table with a PK column of type uniqueidentifier.
I am trying to write an update statement from C#, where I have the identifier as a string.
Here is the code I am trying:
string sql_start = "update SecurityUserGroup set ";
int paramPos = 0;
var paramList = new List<SqlParameter>();
if (roleName != null)
{
sql_start += " RoleName = '{" + paramPos + "}'";
paramList.Add(new SqlParameter(""+paramPos, roleName));
paramPos++;
}
if (activeDirectoryGroup != null)
{
sql_start += " ActiveDirectoryGroup = '{" + paramPos + "}'";
paramList.Add(new SqlParameter(""+paramPos, activeDirectoryGroup));
paramPos++;
}
//sql_start += " where SecurityUserGroupId = cast('{" + paramPos + "}' as uniqueidentifier)";
//sql_start += " where SecurityUserGroupId = convert(uniqueidentifier, '{" + paramPos + "}')";
sql_start += @" where SecurityUserGroupId = '{" + paramPos + @"}'";
paramList.Add(new SqlParameter(""+paramPos, new Guid(id)));
//paramList.Add(new SqlParameter(""+paramPos, id));
SqlHelper.ExecSql(sql_start, paramList);
The SqlHelper.ExecSql function does this:
public static void ExecSql(string sql, List<SqlParameter> parms)
{
using (SqlConnection con = GetConnection())
{
SqlCommand command = new SqlCommand(sql, con) {CommandType = CommandType.Text};
foreach (SqlParameter parm in parms)
{
command.Parameters.Add(parm);
}
command.ExecuteNonQuery();
}
}
But I either get invalid syntax or "Conversion failed when converting from a character string to uniqueidentifier"
I previously had this problem on the extraction and ended up putting the conversion into a stored procedure and it seems I will need to make this into a stored procedure too.
Thanks in advance for any thoughts/tips on this.
EDIT: A sample id looks like this "45d9ec51-1e52-49d8-9139-51f18fe13563", which looks like what I see on the table via Management Studio.
EDIT2: Here is the code that worked in the end (using @ instead of {}):
var sql_start = new StringBuilder("update SecurityUserGroup set ");
int paramPos = 0;
var paramList = new List<SqlParameter>();
if (roleName != null)
{
sql_start.Append(" RoleName = @" + paramPos);
paramList.Add(new SqlParameter("@"+paramPos, roleName));
paramPos++;
}
if (activeDirectoryGroup != null)
{
if (paramPos > 0) sql_start.Append(",");
sql_start.Append(" ActiveDirectoryGroup = @" + paramPos);
paramList.Add(new SqlParameter("@"+paramPos, activeDirectoryGroup));
paramPos++;
}
sql_start.Append(" where SecurityUserGroupId = @id");
paramList.Add(new SqlParameter("@id", id));
SqlHelper.ExecSql(sql_start.ToString(), paramList);
Regards, Chris