此查询给出了错误:“建议'附近的语法不正确。”
SELECT(SELECT COUNT(*) FROM CONTAINSTABLE(Products,keywords,Suggestion)) InventoryRank
FROM (
SELECT Suggestion FROM aTable
)
我如何给出相同的结果?
答案 0 :(得分:1)
CONTAINSTABLE
的第3个参数必须是文字或变量,它不能是列名。如果您需要每个建议的计数,您可以尝试以下方法:
DECLARE @suggestion varchar(100);
DECLARE @result table (Suggestion varchar(100), Result int);
DECLARE csr CURSOR FOR SELECT Suggestion FROM aTable;
FETCH NEXT FROM csr INTO @suggestion;
WHILE @@FETCH_STATUS = 0 BEGIN
INSERT INTO @result (Suggestion, Result)
SELECT @suggestion, (SELECT COUNT(*) FROM CONTAINSTABLE(Products,keywords,@suggestion));
FETCH NEXT FROM csr INTO @suggestion;
END
CLOSE csr;
DEALLOCATE csr;
SELECT * FROM @result;
MSDN CONTAINSTABLE (Transact-SQL)文档。
答案 1 :(得分:0)
CONTAINSTABLE无法在搜索条件中使用表列。你可以这样做:
DECLARE @search nvarchar(4000)
SELECT @search = STUFF((
SELECT '*" or "' + Suggestion
FROM aTable
FOR XML PATH('')
),1,6,'') +'*"'
--That will give you string like "sug1*" or "sug2*" or "sug3*" to search
--You can make whatever you need string. F.e. "sug1" or "sug2" or "sug3"
SELECT COUNT (*)
FROM CONTAINSTABLE(searched_table,searched_column,@search)
修改强>
如果每个InventoryRank
需要不同的Suggestion
,则可以使用动态SQL和临时表:
IF OBJECT_ID(N'##temp') IS NOT NULL DROP TABLE ##temp
CREATE TABLE ##temp (
Suggestion nvarchar(max),
InventoryRank int
)
DECLARE @sql nvarchar(max)
SELECT @sql = (
SELECT N'INSERT INTO ##temp SELECT '''+Suggestion+''' as Suggestion, COUNT (*) as InventoryRank FROM CONTAINSTABLE(searched_table,searched_column,'''+Suggestion+''');'
FROM aTable
FOR XML PATH('')
)
--PRINT(@sql)
EXEC sp_executesql @sql
SELECT *
FROM ##temp
PRINT会给你查询:
INSERT INTO ##temp SELECT 'sug1' as Suggestion, COUNT (*) as InventoryRank FROM CONTAINSTABLE(searched_table,searched_column,'sug1');
INSERT INTO ##temp SELECT 'sug2' as Suggestion, COUNT (*) as InventoryRank FROM CONTAINSTABLE(searched_table,searched_column,'sug2');
所以你不需要WHILE循环或CURSOR来遍历来自aTable
的所有行