如何在Sql Server中使用like运算符参数化查询

时间:2017-08-16 08:47:01

标签: sql sql-server

我正在尝试使用like运算符参数化Sql Query但它不起作用。搜索条件和搜索文本都将通过变量。这就是我在做什么

declare @Query nvarchar(500), @SearchBy nvarchar(50) = 'PtName', @SearchText nvarchar(50) = 'Sh'
set @Query = 'select Id, PtName, Y, M, D, Sex, PtCode, ReceiptDate, ReferBy, RefDrCd, PtTitle, NetAmount, IncentiveAmount, PaidAmount, DueAmount, Investigation, LabCode, LabName, DiscAmount, PNo  FROM DiagMain where '+@SearchBy+' like '+@SearchText+' %'
    exec(@Query)

请帮助。

1 个答案:

答案 0 :(得分:3)

DECLARE @Query NVARCHAR(500), @SearchBy NVARCHAR(50) = 'PtName', @SearchText NVARCHAR(50) = 'Sh'
SET @Query = 'select Id, PtName, Y, M, D, Sex, PtCode, ReceiptDate, ReferBy, RefDrCd, PtTitle, NetAmount, IncentiveAmount, PaidAmount, DueAmount, Investigation, LabCode, LabName, DiscAmount, PNo  FROM DiagMain where '+@SearchBy+' like '''+@SearchText+'%'''

PRINT @Query
EXEC(@Query)