我有一个SQL Server表值函数,由我创建,我已经粘贴了下面的创建脚本
CREATE FUNCTION [dbo].[getTableFromString]
(
@String AS nvarchar(max)
)
RETURNS @ReturnTable TABLE ( StringValues nvarchar(10) )
AS begin
if (SELECT CHARINDEX(',', @String)) = 0
begin
insert into @ReturnTable (StringValues) values (subString(@String,1,len(@String)));
end
else
begin
while (SELECT CHARINDEX(',', @String)) > 0
begin
insert into @ReturnTable (StringValues) values (subString(@String,1,CHARINDEX(',', @String)-1));
set @String = subString(@String,CHARINDEX(',', @String)+1,len(@String));
if (SELECT CHARINDEX(',', @String)) = 0
begin
insert into @ReturnTable (StringValues) values (subString(@String,1,len(@String)));
end
end
end
return ;
end
我正在使用此功能,如下所示
Select sum(NetSales)
from vwxsalesall
where Company = 'rs'
and storecode = (select cPrimaryStockRoomCode from CompanyMaster.CompanyProfileDetail where cCompanyNo = 'rs' and cSecondaryStockRoomCode = 'R01B')
and trandate >= '2012-01-01'
and trandate <= '2012-01-31'
and (
brand in (
select StringValues from dbo.getTableFromString(
select vIncludedBrandCodes
from StockRoomTargetData.MonthlyTarget
where cCompanyNo = 'rs'
and cSecondaryStockRoomCode = 'R01B'
and nYear = 2012
and nMonth = 8
)
)
)
不幸的是我收到了这个错误
Msg 156,Level 15,State 1,Line 10
关键字“select”附近的语法不正确。
Msg 102,Level 15,State 1,Line 16
')'附近的语法不正确。
请帮帮我
答案 0 :(得分:0)
您需要在子查询周围添加另一组括号,例如
select StringValues from dbo.getTableFromString(( { your-subquery }))
^ ^
(parenthesis added)
第一组父类在语法上属于TVF调用,第二组用于子查询。
现在你的查询:
Select sum(NetSales)
from vwxsalesall
where Company = 'rs'
and storecode = (select cPrimaryStockRoomCode from CompanyMaster.CompanyProfileDetail where cCompanyNo = 'rs' and cSecondaryStockRoomCode = 'R01B')
and trandate >= '2012-01-01'
and trandate <= '2012-01-31'
and (
brand in (
select StringValues from dbo.getTableFromString((
select vIncludedBrandCodes
from StockRoomTargetData.MonthlyTarget
where cCompanyNo = 'rs'
and cSecondaryStockRoomCode = 'R01B'
and nYear = 2012
and nMonth = 8
))
)
)