在CONTAINS谓词(SQL Server)中使用连接

时间:2016-01-19 22:57:16

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

我试图在CONTAINS谓词中使用连接,所以我能够使用变量;但是,我收到了错误:

  

'+'附近的语法不正确。

以下是查询:

DECLARE @search varchar;
SET @search = 'blue dude';

SELECT distinct itemno, basedescription,upc,CAST((SELECT [UNITPRICE] 
FROM PPPLTD.dbo.[ICPRICP] WHERE [ITEMNO] = replace([DataWarehouse].[dbo].[ORDERFORMDUMP].[ITEMNO],'-','') 
AND [PRICELIST] = (select top 1 priclist from PPPLTD.dbo.ARCUS 
where IDCUST = (select top 1 CUSTID from PPPLTD.dbo.WEBLOGINACCESS where [USER] = 'user')) 
and [CURRENCY] = 'CDN' 
and DPRICETYPE = 1) AS DECIMAL(18,2)),caseqty 
FROM [DataWarehouse].[dbo].[ORDERFORMDUMP] 
where (allowinbc = 'Yes' or allowinab = 'Yes') 
and (contains(*, '"'+replace(@search,' ','" and "')+'"') 
or (select top 1 1 from PPPLTD.dbo.ICITEMO where OPTFIELD like 'UPC%' 
and VALUE like '%'+@search+'%' and ITEMNO = DataWarehouse.dbo.ORDERFORMDUMP.itemno) is not null) 
order by ORDERFORMDUMP.BASEDESCRIPTION

当我有contains(*, ' "blue" and "dude" ')

时,查询运行正常

另外,我不确定我是否能够在那里使用REPLACE功能。我需要它能够用“”替换空格。

使用LIKE关键字代替CONTAINS不是我的选择。

谢谢。

1 个答案:

答案 0 :(得分:1)

您基本上尝试在一个语句中使用动态SQL和T-SQL,这是您无法做到的。

您需要动态创建SQL,然后执行sql文本

DECLARE @sql varchar(max);
DECLARE @cond varchar(max)
DECLARE @search varchar(max);
SET @search = 'blue dude';
SET @cond = replace(@search,' ','" and "');
SET @sql = 'SELECT distinct itemno, basedescription,upc,CAST((SELECT [UNITPRICE] FROM PPPLTD.dbo.[ICPRICP] WHERE [ITEMNO] = replace([DataWarehouse].[dbo].[ORDERFORMDUMP].[ITEMNO],''-'','''') AND [PRICELIST] = (select top 1 priclist from PPPLTD.dbo.ARCUS where IDCUST = (select top 1 CUSTID from PPPLTD.dbo.WEBLOGINACCESS where [USER] = ''user'')) and [CURRENCY] = ''CDN'' and DPRICETYPE = 1) AS DECIMAL(18,2)),caseqty FROM [DataWarehouse].[dbo].[ORDERFORMDUMP] where (allowinbc = ''Yes'' or allowinab = ''Yes'') '
SET @sql = @sql + 'and (contains(*, ''"' + @cond + '"'') '
SET @sql = @sql + 'or (select top 1 1 from PPPLTD.dbo.ICITEMO where OPTFIELD like ''UPC%'' and VALUE like ''%' + @search + '%'''
SET @sql = @sql + 'and ITEMNO = DataWarehouse.dbo.ORDERFORMDUMP.itemno) is not null) order by ORDERFORMDUMP.BASEDESCRIPTION'

print @sql -- This will help you see the actual resulting text for testing
EXECUTE (@sql)