2

我的存储过程如下所示:

Alter PROCEDURE [dbo].[productfilter_whatsnew]
   @query1 nvarchar(max),
   @query2 nvarchar(max),
   @date date,
   @pid varchar(5)
AS
   select * 
   FROM Productcolorimage pci  
   where entry_date > @date 
     and selectproduct = @pid + ' ' + @query1 
   order by @'@query2'
GO

我的函数传递值

public DataTable productfilter_whatsnew(ProductBAL objbal)
{
    DataTable dt = new DataTable();

    using (SqlConnection conn = new SqlConnection(strconn))
    {
        conn.Open();
        SqlCommand cmd = new SqlCommand("productfilter_whatsnew", conn);
        cmd.CommandType = CommandType.StoredProcedure;
        SqlParameter[] para = {
                               new SqlParameter("@query1","and colorid in('3')"),
                                new SqlParameter("@query2","pid ASC"),
                                new SqlParameter("@date","14-09-2013"),
                                new SqlParameter("@pid","1")
                              };
        try
        {
            cmd.Parameters.AddRange(para);
            SqlDataAdapter d = new SqlDataAdapter(cmd);
            d.Fill(dt);
            conn.Close();
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
    return dt;
}

但是显示不同的放置错误@query1@query2......

4

2 回答 2

2

如果您确实确定要执行此操作,请使用动态 SQL。但请务必先阅读有关SQL 注入的内容。

alter procedure [dbo].[productfilter_whatsnew]
(
    @query1 nvarchar(max),
    @query2 nvarchar(max),
    @date date,
    @pid varchar(5)
)
as
begin
    declare @stmt nvarchar(max)

    select @stmt= '
        select * 
        from Productcolorimage as pci
        where entry_date > @date and selectproduct = @pid'

    select @stmt = @stmt + ' ' + @query1
    select @stmt = @stmt + ' order by ' + @query2

    -- passing parameters into sp by names, easier to maintain in the future
    exec sp_executesql
        @stmt = @stmt,
        @params = N'@date date, @pid varchar(5)',
        @date = @date,
        @pid = @pid;
end
于 2013-09-14T12:01:22.383 回答
1

如果你真的需要,你可以改变你的过程来调用sp_executesql。您确定不能使用 Entity Framework 或 NHibernate 或任何其他 ORM 库吗?

Alter PROCEDURE [dbo].[productfilter_whatsnew]
@query1 nvarchar(max),
@query2 nvarchar(max),
@date date,
@pid varchar(5)
AS
BEGIN
    declare @sql nvarchar(1000)
    declare @ParmDefinition nvarchr(1000)
    SET @ParmDefinition = N'@date date, @pid varchar(5)';

    set @sql = N'select * FROM Productcolorimage pci  where entry_date>@date and selectproduct=@pid ' + @query1 + ' order by ' + @query2

    EXECUTE sp_executesql @sql, @ParmDefinition, @date=@date, @pid=@pid;
END
GO
于 2013-09-14T11:53:05.690 回答