2

I have an SQL Server database table created by deploying the following description in a .dbproj project:

CREATE TABLE [dbo].[Tasks] ( TaskId uniqueidentifier primary key, State int not null, ) 

and I want to insert a row into that table with the following code:

using( SqlTransaction transaction = connection.BeginTransaction() ) { using( SqlCommand command = connection.CreateCommand() ) { command.CommandText = "INSERT INTO Tasks VALUES( \"" + Guid.NewGuid().ToString() + "\", 0)"; command.Transaction = transaction; command.ExecuteNonQuery(); transaction.Commit(); } } 

when ExecuteNonQuery() runs an exeption is thrown saying

The name [the string representation of the GUID I passed] is not permitted in this context.

What's up? I did the same to insert data into an SQLite table previously and it worked. How do I pass a GUID into an SQL INSERT statement?

2
  • Use paramterised query Commented Mar 17, 2011 at 11:03
  • Don't use single quotes - use a parametrized query instead! Much safer.... can you spell SQL injection attack? Commented Mar 17, 2011 at 11:03

1 Answer 1

12

Use a parameterized query, like so:

command.CommandText = "INSERT INTO Tasks VALUES( @id, 0)"; command.Parameters.Add( "@id", SqlDbType.UniqueIdentifier, 16 ).Value = value; 

This way, the database driver formats the value for you. This is a good practice that will also help protect your database from SQL Injection attacks.

Alternatively, you could let the database generate the guid for you:

command.CommandText = "INSERT INTO Tasks VALUES( NEWID(), 0)";
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.