WHERE子句具有STUFF功能

时间:2015-04-17 18:28:17

标签: sql sql-server tsql

我想做一个查询,我得到一个单独的ID然后用逗号,并把它放在我的where子句上。

但发生以下错误

  

Msg 245,Level 16,State 1,Line 10
  转换nvarchar值'2998,2999,3000,3001,3002,3003,3004,3005,3006,3007,3008,3009,3010,3011,3012,3013,3482,3483,3484,3485,3486时转换失败, 3487,3488,3489,3490,3491,3492,3493,3494,3495,...

我尝试了一些演员,但是没有效果。

示例查询:

SELECT A.ID, A.ID_PERIODO_GESTAO, A.ID_FILIAL, A.ID_RESPONSAVEL_AREA, A.ID_PARENT, A.ID_SOURCE, A.COD_AREA, A.DESC_AREA, A.ATIVO, A.USER_LOGIN_RESP, A.NOME_RESP, A.DESC_FILIAL, A.COD_AREA_SUP, A.FOTO_PATH, 
A.COLABORADOR_ID,
CASE WHEN (SELECT COUNT(B.ID_COLABORADOR) FROM COLABORADOR_AREA B WHERE B.ID_AREA = A.ID GROUP BY B.ID_AREA) IS NULL THEN 0 ELSE 
(SELECT COUNT(B.ID_COLABORADOR) FROM COLABORADOR_AREA B WHERE B.ID_AREA = A.ID GROUP BY B.ID_AREA) END AS QTD_COLABORADORES,
A.LEVEL_TREE,LEN(A.LEVEL_TREE),

STUFF(
           (SELECT ',' + CAST(VW.ID AS VARCHAR(10))
            FROM VW_AREA VW
            WHERE LEN(VW.LEVEL_TREE) > LEN(A.LEVEL_TREE) 
            AND VW.ID_PERIODO_GESTAO = 2                 
            FOR XML PATH('')), 1, 1, '')

FROM VW_AREA A
LEFT JOIN dbo.COLABORADOR_AREA ON dbo.COLABORADOR_AREA.ID_COLABORADOR = A.COLABORADOR_ID        
WHERE A.ID_FILIAL IN (9) AND A.ID_PERIODO_GESTAO = 2

UNION

SELECT A.ID, A.ID_PERIODO_GESTAO, A.ID_FILIAL, A.ID_RESPONSAVEL_AREA, A.ID_PARENT, A.ID_SOURCE, A.COD_AREA, A.DESC_AREA, A.ATIVO, A.USER_LOGIN_RESP, A.NOME_RESP, A.DESC_FILIAL, A.COD_AREA_SUP, A.FOTO_PATH, 
A.COLABORADOR_ID,
CASE WHEN (SELECT COUNT(B.ID_COLABORADOR) FROM COLABORADOR_AREA B WHERE B.ID_AREA = A.ID GROUP BY B.ID_AREA) IS NULL THEN 0 ELSE 
(SELECT COUNT(B.ID_COLABORADOR) FROM COLABORADOR_AREA B WHERE B.ID_AREA = A.ID GROUP BY B.ID_AREA) END AS QTD_COLABORADORES,
A.LEVEL_TREE, LEN(A.LEVEL_TREE),

    STUFF(
            (SELECT ',' + CAST(VW.ID AS VARCHAR(10))
             FROM VW_AREA VW 
             WHERE LEN(VW.LEVEL_TREE) > LEN(A.LEVEL_TREE) 
             AND VW.ID_PERIODO_GESTAO = 2           
             FOR XML PATH('')), 1, 1, '') AS 

FROM VW_AREA A
LEFT JOIN dbo.COLABORADOR_AREA ON dbo.COLABORADOR_AREA.ID_COLABORADOR = A.COLABORADOR_ID
JOIN CTE4 ON A.ID = CTE4.ID_PARENT
WHERE A.ID_PERIODO_GESTAO = 2 
AND (A.ID IN (CTE4.ID_PARENT))

RESULT

QTD_COLABORATOR    LEVEL_TREE     QTD_CARACTER_IN_LEVEL_TREE
1                  002            3

使用STUFF函数的最后一列将包含类似

的数据

2997,2998,2999,3000,3001,3002,3003,3004,3005,3006,3007,3008,3009,3010,3011,3012,3013,3014,3015,3016,3017

这是在LEVEL_TREE

中包含超过3个字符的所有ID

2 个答案:

答案 0 :(得分:3)

那永远不会奏效。你正试图在字符串中使用比较器。因此语法错误。你有什么理由不这样做吗?

SELECT SUM(A.ID) 
 FROM COLABORATOR A 
 WHERE A.ID IN (SELECT VW.ID FROM VW_AREA VW)

答案 1 :(得分:0)

你好STUFF会让你的值以逗号分隔,并且IN子句会期望一个INT的结果集,所以它会崩溃, 您可以使用动态字符串执行来执行此操作:

SET @sqlCommand = 'SELECT ' + @columnList + ' FROM customers WHERE City = ' + @city
EXEC (@sqlCommand)