我需要帮助。 我写这个查询
SELECT SUM(fi.etiliquido) FROM fi WHERE fi.fno IN (
SELECT * from divideString(
SELECT TOP 1 REPLACE(CAST( u.nrdoc AS nvarchar),'/',',') FROM u_ups1 as u WHERE 1057 IN (
SELECT * FROM divideString(REPLACE(CAST(u.nrdoc AS nvarchar),'/',','))
)
)
)
但是sql server返回此错误
消息156,级别15,状态1,行4关键字附近的语法不正确 '选择&#39 ;. Msg 102,Level 15,State 1,Line 7语法不正确 ')'
我不知道为什么。 你能救我吗?
UPDATE divideString是一个函数获取一个字符串并返回该字符串中的数字
CREATE FUNCTION divideString (@InStr VARCHAR(MAX))
RETURNS @TempTab TABLE
(id int not null)
AS
BEGIN
SET @InStr = REPLACE(@InStr + ',', ',,', ',')
DECLARE @SP INT
DECLARE @VALUE VARCHAR(1000)
WHILE PATINDEX('%,%', @INSTR ) <> 0
BEGIN
SELECT @SP = PATINDEX('%,%',@INSTR)
SELECT @VALUE = LEFT(@INSTR , @SP - 1)
SELECT @INSTR = STUFF(@INSTR, 1, @SP, '')
INSERT INTO @TempTab(id) VALUES (@VALUE)
END
RETURN
END
答案 0 :(得分:1)
你需要在子查询周围加上括号(in
子查询除外),所以:
SELECT SUM(fi.etiliquido)
FROM fi
WHERE fi.fno IN (SELECT d.val
FROM divideString( (SELECT TOP 1 REPLACE(CAST( u.nrdoc AS nvarchar(max)), '/', ',')
FROM u_ups1 as u
WHERE 1057 IN (SELECT d.val
FROM divideString(REPLACE(CAST(u.nrdoc AS nvarchar(max)), '/', ',') d(val)
)
)
) d(val)
);
此外,使用TOP
而没有ORDER BY
通常是可疑的。
不建议在单个列中存储多个值。但是,我不认为你需要一个表值函数。 LIKE
应该有效:
SELECT SUM(fi.etiliquido)
FROM fi
WHERE EXISTS (SELECT 1
FROM (SELECT TOP 1 u.nrdoc
FROM u_ups1 u
WHERE '/' + u.nrdoc + '/' LIKE '%/1057/%'
) u
WHERE '/' + u.nrdoc + '/' LIKE '%/' + fi.fno + '/%'
);
你可能想要的东西:
而且,你想要的逻辑可能就像这样简单:
SELECT SUM(fi.etiliquido)
FROM fi
WHERE EXISTS (SELECT 1
FROM u_ups1 u
WHERE '/' + u.nrdoc + '/' LIKE '%/1057/%' AND
'/' + u.nrdoc + '/' LIKE '%/' + fi.fno + '/%'
);