比变量中的Like语句更多

时间:2016-02-29 13:42:33

标签: sql sql-server sql-server-2008 dml

为什么这项工作:

SELECT * FROM Companies  WHERE CompanyCode LIKE '%' AND BusinessUnitShortName LIKE 'CO%'

虽然意味着这不起作用:

DECLARE @WHERECondition NVARCHAR(200) = ''
SET @WHERECondition = '''%'' AND BusinessUnitShortName LIKE ''CO%'''

SELECT * FROM Companies WHERE CompanyCode LIKE  @WHERECondition
SELECT  @WHERECondition

2 个答案:

答案 0 :(得分:1)

要完成这项工作,您需要使用动态sql,如

DECLARE @WHERECondition NVARCHAR(200) = ''
SET @WHERECondition = '''%'' AND BusinessUnitShortName LIKE ''CO%'''
declare @sql nvarchar(Max)

Set @sql='SELECT * FROM Companies WHERE CompanyCode LIKE'+@WHERECondition

exec sp_executesql @sql

如果您没有使用动态sql,那么您需要提供列名,因为SQL解析器将在解析查询时查找列,如果找不到则会导致错误。

答案 1 :(得分:0)

您需要使用动态SQL来实现您想要的效果。您当前的方法会被评估为:

SELECT * 
FROM Companies 
WHERE CompanyCode LIKE '''%'' AND BusinessUnitShortName LIKE ''CO%'''

你真正想要的更像是这样:

DECLARE @sql NVARCHAR(MAX) = ''
DECLARE @WHERECondition =  '''%'' AND BusinessUnitShortName LIKE ''CO%'''

SET @sql = 'SELECT * FROM Companies WHERE CompanyCode LIKE ' + @WHERECondition
EXEC(@sql);

将评估:

SELECT * FROM Companies WHERE CompanyCode LIKE '%' AND BusinessUnitShortName LIKE 'CO%'