1

I am executing a SQL statement in SQL Server Express

insert into dscl_sql_log (user_name, sql_time, sql) 
values ('ADMIN', '2/17/2014 7:05:45 PM', 'select * from cn_fieldsurvey_trn where unit_code = '03' and rownum < 10')

It gives an error message that **incorrect syntax near '03'**

1
  • You should use double quotas around string constant = ''03'' Commented Feb 17, 2014 at 13:41

4 Answers 4

1
 insert into dscl_sql_log (user_name, sql_time, sql) values ('ADMIN', '2/17/2014 7:05:45 PM', 'select * from cn_fieldsurvey_trn where unit_code = ''03'' and rownum < 10')

If you are getting value from textbox then it is highly recommended to use parameterized query to prevent SQL Injection Attacks and avoid explicitly escaping single characters in value being passed.

       string query=  @"insert into dscl_sql_log (user_name, sql_time, sql) values  " +
            " (" +
                  @"'ADMIN', '2/17/2014 7:05:45 PM',@sql "+
             ")";

        using (var cmd = new SqlCommand(query, conn))
        {
            cmd.Parameters.AddWithValue("@sql", txtbox.Text);

            cmd.ExecuteNonQuery();
        }
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for answering, but what if I am getting a value of sql column from a text box. Actually string LogQry = "insert into dscl_sql_log (user_name, sql_time, sql) values ('"+user_code+"', '" + DateTime.Now + "', '"+SqlText.ToString()+"')"; above is my code in .cs page.
You can use my answer. But since you are dynamically building that query just replace one quote for two quotes in that ToString. Btw your app is likey to be prone o SQL inject attacks.
@jean parameterized query should be used
0

You need to replace that quotes with 2 quotes, you are getting a error due to not escaping quotes.

insert into dscl_sql_log (user_name, sql_time, sql) values 
    ('ADMIN', '2/17/2014 7:05:45 PM',
replace('select * from cn_fieldsurvey_trn where unit_code = '03' and rownum < 10','''',''''''))

Comments

0

Or you can use like this:

insert into dscl_sql_log (user_name, sql_time, sql) values ('ADMIN', '2/17/2014 7:05:45 PM', 'select * from cn_fieldsurvey_trn where unit_code = ' + '03' + ' and rownum < 10')

But be careful whit SQL Injection issues like they said!

Comments

0

try:

insert into dscl_sql_log (user_name, sql_time, sql) 
values ('ADMIN', '2/17/2014 7:05:45 PM', 'select * from cn_fieldsurvey_trn where unit_code = ''03'' and rownum < 10')

use 2 quote in the strings.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.