Using C# SQL Parameterization on Column Names

后端 未结 3 885
再見小時候
再見小時候 2021-01-27 15:52

I\'m having a problem. I want this to work, but it doesn\'t:

SqlDataSource.SelectCommand = \"SELECT blah1, blah2 FROM myTable WHERE @ColumnName = @Value\";

SqlD         


        
3条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-27 16:35

    I'm afraid you can't do that, what you can do instead is a little trick:

    SELECT blah1, blah1 FROM myTable 
    WHERE (@blah1 is null or blah1 = @blah1)
       or (@blah2 is null or blah2 = @blah2)
    

    and provide all params @blah1, @blah2 but only assign those you need.

    NB solution that Mike Christensen offering you is basically building string with right condition, which in simplest case would be

    public bool BuildQueryWithCondition(string fieldName, string fieldValue) {
       var queryTemplate = "SELECT blah1, blah1 FROM myTable WHERE {0} = @Value"
         , query = string.Format(queryTemplate, fieldName)
       SqlDataSource.SelectCommand = query;
       SqlDataSource.SelectParameters.Add("Value", System.Data.DbType.String, fieldValue);
    }
    

提交回复
热议问题