参数化SQL值语法问题

时间:2011-06-24 18:35:55

标签: c# sql-server parameterized-query

我不确定问题是什么,但我的代码如下:

function() {
string sqltext2;
sqltext2 = "INSERT into myTable";
SqlCommand myCommand2 = new SqlCommand(sqltext2, MyConnection2);

if (cond1) {

    sqltext2 = sqltext2 + "SELECT" + "@initOwnerFirstName" + "," + "@ownerFirstName"  + "UNION ALL ";
    SqlParameter param = new SqlParameter();
    param.ParameterName = "@initOwnerFirstName";
    param.Value = initOwnerFirstName;
    SqlParameter param2 = new SqlParameter();
    param2.ParameterName = "@ownerFirstName";
    param2.Value = owner.FirstName;
    myCommand2.Parameters.Add(param);
    myCommand2.Parameters.Add(param2);

我对参数化SQL完全不熟悉,但语法似乎对我而言。我一直得到的错误是:

必须声明标量变量“@initOwnerFirstName”。 我正在编写这样的语句的原因是因为我打算将多个其他if语句添加到SQLtext

编辑:这是if语句之后的完整部分代码,因为没有其他变量,我的语法没有意义。这是在JYelton建议之后清理的,但我仍然遇到同样的错误。

sqltext2 = sqltext2 + "SELECT" + "'" + currentUserId2 + "'," + "'" +  owner.Id.ToString() + "'," + "'" + DateTime.Now + "'," + "'FirstName', @initOwnerFirstName, @ownerFirstName UNION ALL ";
myCommand2.Parameters.AddWithValue("initOwnerFirstName", initOwner.FirstName);
myCommand2.Parameters.AddWithValue("OwnerFirstName", owner.FirstName);

2 个答案:

答案 0 :(得分:2)

问题可能是你没有空格连接你的字符串。您也不需要连接。请参阅下面的更新:

function() {
string sqltext2;
sqltext2 = "INSERT into dbo.OwnerChanges ";
SqlCommand myCommand2 = new SqlCommand(sqltext2, MyConnection2);

if (cond1) {
    //no concatenating
    sqltext2 = sqltext2 + " SELECT @initOwnerFirstName , @ownerFirstName UNION ALL ";
    SqlParameter param = new SqlParameter();
    param.ParameterName = "@initOwnerFirstName";
    param.Value = initOwnerFirstName;
    SqlParameter param2 = new SqlParameter();
    param2.ParameterName = "@ownerFirstName";
    param2.Value = owner.FirstName;
    myCommand2.Parameters.Add(param);
    myCommand2.Parameters.Add(param2);

我不确定你的其余代码是做什么的,但我怀疑你在所有代码的末尾留下了一个尾随的UNION ALL。您可能只需将每个子查询放入一个数组并在其上使用String.Join即可获益。

<强>更新

我想我看到了这个问题。您需要更新CommandText而不是原始字符串。所以改变这个:

sqltext2 = sqltext2 + " SELECT @initOwnerFirstName , @ownerFirstName UNION ALL ";

到此:

myCommand2.CommandText= sqltext2 + " SELECT @initOwnerFirstName , @ownerFirstName UNION ALL ";

答案 1 :(得分:2)

以下是参数化查询的工作原理:

using (SqlConnection conn = new SqlConnection("connectionstring"))
{
    using SqlCommand cmd = conn.CreateCommand())
    {
        cmd.CommandText = @"INSERT INTO mytable
            (initOwnerFirstName, ownerFirstName)
            VALUES (@initOwnerFirstName, @ownerFirstName);";
        cmd.Parameters.AddWithValue("initOwnerFirstName", initOwner.FirstName);
        cmd.Parameters.AddWithValue("ownerFirstName", owner.FirstName);
        // ... execute query
    }
}

看起来你正在插入myTable SELECT语句的结果,但是你试图传递列名应该去的参数。参数将用值替换@variablename:因此:参数用于值,而不是列名。

对于多个值,请使用括号指定集合,以逗号分隔:

INSERT INTO mytable (col1, col2) VALUES ("a", "b"), ("c", "d"), ("e", "f");

您可以适当修改查询字符串以符合此语法。

更多信息:SQL Insert Syntax