将存储过程中的多个参数传递给QueryString参数

时间:2013-04-05 15:35:04

标签: sql-server stored-procedures querystringparameter

如何将存储过程中的两个SQL参数传递给WHERE子句中的查询字符串?我遇到的问题是@iField。如果我删除它并用InfoID LIKE'%'+ @iSearch +'%'替换它,它可以工作,但我需要添加@iField。

WHERE CustomerID = @CustomerID AND @iField LIKE '%' + @iSearch + '%'

3 个答案:

答案 0 :(得分:1)

至于你已经在使用程序

Declare @Query nvarchar(max)
Select @Query=
'
Select * from dbo.Invoice
WHERE CustomerID = '+Cast(@CustomerID as Varchar(20)) 
+' AND ['+ @iField +'] LIKE ''%' + @iSearch + '%''
'

--Print @Query
Exec(@Query)

答案 1 :(得分:0)

T-SQL不允许你为对象名称替换变量(它会很方便,但不会这样)。真的有两个选择:

1)使用动态SQL,例如sp_executesql(http://www.techrepublic.com/blog/datacenter/generate-dynamic-sql-statements-in-sql-server/306

2)使用IF ... ELSE,例如

IF @iField = 'InfoId'
     SELECT ...
     WHERE CustomerID = @CustomerID AND InfoId LIKE '%' + @iSearch + '%'
ELSE IF @iField = '<some other field>'
     SELECT ...
     WHERE CustomerID = @CustomerID AND <some other field> LIKE '%' + @iSearch + '%'
etc.

答案 2 :(得分:0)

如果我理解正确,您只是想将like运算符限制为特定列?

declare @yourTable table (i int, FirstName varchar(10), LastName varchar(10))
insert into @yourTable
    select 1, 'john', 'doe' union all
    select 2, 'jane', 'doe';


declare @iField varchar(10),
        @iSearch varchar(10);


select  @iField = 'FirstName',
        @iSearch = 'j'


select  *
from    @yourTable
where   (@iField = 'FirstName' and FirstName like '%' + @iSearch + '%') or
        (@iField = 'LastName' and LastName like '%' + @iSearch + '%')