Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating a literal for a UNIQUEIDENTIFIER in an INSERT INTO query

I am writing a utility, C#, to import a large CSV with about 80 columns into a SQL Server 2008 table.

The CSV needs manipulation before import e.g. merging some columns, converting dates etc. I am therefore constructing an INSERT INTO statement like so:

INSERT INTO table VALUES ('abc','blah',...)

My problem is that the table contains a column of type UNIQUEINDENTIFIER. It's a problem because I would like to re-use an existing method which takes a collection of values and returns the string of values to pop directly into my INSERT INTO statement with apostrophes dealt with, injection attacks munged out etc.

Is there a way of generating a valid literal for a UNIQUEIDENTIFIER that I can pass to this method? I tried Guid.NewGuid.ToString(), which gives me a literal like so 'bfdb0297-2018-4555-ac12-88064944a671', but my query then errors with a data truncation exception. I also tried with the hyphens removed. I expected 32 hex characters to work.

I know that a parameterised query is the correct way to go but that would mean a significant re-work of existing code.

I'm pretty good with C# and bluff-worthy with SQL Server.

[EDIT]

I've done several things. First, wrote a query which updates that column with Guid.NewGuid at it works. Therefore, the truncation error is not from there. Checking the SQL Server reference leads me to believe that a truncation error is not returned from a bad value in an id column, rather it's an invalid value error. I've also taken into account Aaron's comment that significant work is not an excuse for not doing it right and have created a method to generate a parameterised query which is now working fine.

Many thanks to all responders.

like image 423
Simon Avatar asked Dec 01 '22 22:12

Simon


1 Answers

A literal UNIQUEIDENTIFIER in SQL Server looks like this:

SELECT {guid'8DEC377B-6D75-424B-AE01-D3727993C7F6'}

As seen in the documentation:

It is a sequence formed by the keyword GUID followed by hexadecimal digits in the form known as registry format: 8-4-4-4-12 enclosed in single quotes.

No one seems to know this. This is the first language I have seen that actually has literal GUID/UUIDs.

like image 141
Nick Whaley Avatar answered Dec 23 '22 14:12

Nick Whaley