t-sql命令参数通配符

时间:2012-06-26 18:59:45

标签: c# tsql

我读过很多类似的问题,但答案根本不起作用。在sql select * from HelloRow('o')中运行此函数不会返回任何行。运行HelloRow('one')将返回名为“one”的行。 fillrow方法不做任何事情(只读字符串)。

[Microsoft.SqlServer.Server.SqlFunction(FillRowMethodName = "HelloFillRow", DataAccess = DataAccessKind.Read, TableDefinition="message nchar(20)")]
public static IEnumerable HelloQuery(SqlString like)
{
    ArrayList resultCollection = new ArrayList();

    using (SqlConnection connection = new SqlConnection("context connection=true"))
    {
        connection.Open();

        using (SqlCommand select = new SqlCommand(
            "select name from test where name like @par"
            , connection))
        {
            select.Parameters.Add("par", SqlDbType.NChar, 10).Value = like + "%";
            using (SqlDataReader selectReader = select.ExecuteReader())
            {
                while (selectReader.Read())
                {
                    SqlString nextName = selectReader.GetString(0);
                    resultCollection.Add(nextName.ToString());
                }
            }
        }
    }
    return resultCollection;
}

1 个答案:

答案 0 :(得分:5)

将命令文本更改为:

select name from test where name like @par + '%'

并添加参数:

select.Parameters.Add("par", SqlDbType.NVarChar, 10).Value = like;