2016-02-29 75 views
2

为什么这个工作:比LIKE语句更可变

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 
+1

因为除非您使用动态SQL,否则列名不能包含在变量中。 – xQbert

回答

1

,使这项工作你需要使用动态SQL,如

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

Set @sql='SELECT * FROM Companies WHERE CompanyCode LIKE'[email protected] 

exec sp_executesql @sql 

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

+1

非常感谢你 – user2773107

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); 

这将evalute到:

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

非常感谢你 – user2773107