执行时语法错误

时间:2014-02-17 13:38:27

标签: sql tsql sql-server-express

我正在SQL Server Express中执行SQL语句

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')

它会显示**incorrect syntax near '03'**

的错误消息

4 个答案:

答案 0 :(得分: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')

如果从文本框中获取价值,则强烈建议使用参数化查询来防止 SQL注入攻击,并避免显式转义传递的值中的单个字符。

       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();
        }

答案 1 :(得分:0)

您需要用2引号替换引号,因为没有转义引号而导致错误。

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','''',''''''))

答案 2 :(得分:0)

或者您可以这样使用:

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')

但要小心, SQL注入问题就像他们说的那样!

答案 3 :(得分:0)

尝试:

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')

在字符串中使用2引号。