Search code examples
c#sql-serveradoguiduniqueidentifier

Error "Insufficient result space to convert uniqueidentifier value to char."


Table for the inserts:

CREATE TABLE [dbo].[CcureMessage] 
(
      [CcureMessageId] [UNIQUEIDENTIFIER] NOT NULL,
      [Event] [VARCHAR](20) NULL,
      [Type] [VARCHAR](20) NULL,
      [Message] [VARCHAR](MAX) NOT NULL,
      [Xml] [VARCHAR](4000) NOT NULL,

      CONSTRAINT [PK_CcureMessage] 
          PRIMARY KEY CLUSTERED ([CcureMessageId] ASC)
                      WITH (STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF)  ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO

ALTER TABLE [dbo].[CcureMessage] 
    ADD CONSTRAINT [DF_CcureMessage_CcureMessageId]  
        DEFAULT (NEWID()) FOR [CcureMessageId]
GO

I made the PK table have a default value so that I'm not passing a GUID at all, yet it seems I'm still getting an error related to the guid.

Insert command that works fine through SSMS:

INSERT INTO CcureMessage (Event, Type, Message, Xml) 
VALUES ('event 3', 'type 3', 'big json 3', 'xml-ish');

C# Code:

public void DoInsert(Message msg)
{
    // hard-coding this to set test values
    TopicMessage tm = new TopicMessage();
    tm.Event = "event 1";
    tm.Type = "Type 1";
    tm.Message = "json data message";
    tm.Xml = "xml data goes here";

    string connString = set to correct value;

    string sql = "INSERT INTO CcureMessage (Event, Type, Message, Xml) VALUES (@Event, @Type, @Message, @Xml)";

    using (SqlConnection conn = new SqlConnection(connString))
    {
        conn.Open();
        SqlCommand cmd = new SqlCommand(sql, conn);
        cmd.CommandType = System.Data.CommandType.Text;

        SqlParameter eventParm = new SqlParameter("@Event", tm.CcureMessageId);
        SqlParameter typeParm = new SqlParameter("@Type", tm.Type);
        SqlParameter msgParm = new SqlParameter("@Message", tm.Message);
        SqlParameter xmlParm = new SqlParameter("@Xml", tm.Xml);
        cmd.Parameters.Add(eventParm);
        cmd.Parameters.Add(typeParm);
        cmd.Parameters.Add(msgParm);
        cmd.Parameters.Add(xmlParm);

        cmd.ExecuteNonQuery();
    }
}

Running this results in the error

Insufficient result space to convert uniqueidentifier value to char


Solution

  • The problem seems that you are passing guid to a varchar column in your code

     SqlParameter eventParm = new SqlParameter("@Event", tm.CcureMessageId);
    

    Should be:

    SqlParameter eventParm = new SqlParameter("@Event", tm.Event);