我的动态查询适用于parentku和childsku数据都存在的情况,但是当childsku不在但parentku存在时不起作用。这是不工作的情况......我希望它能处理这两种情况。 ..
IF OBJECT_ID('tempdb..##TEMP_ParentsChild_Products') IS NOT NULL
DROP TABLE ##TEMP_ParentsChild_Products
SET @SQL = 'SELECT
a.'+@Parent_SKU+' AS ''Parent SKU''
,COUNT('+@Child_SKU+') AS ''ChildSKU_Total''
,STUFF((SELECT '','' +'+@Child_SKU+'
FROM ['+@TableName+'] b
WHERE b.'+@Parent_SKU+' = a.'+@Parent_SKU+'
FOR XML PATH('''')),1, 1, '''') AS ''ChildSKU''
INTO ##TEMP_ParentsChild_Products
FROM ['+@TableName+'] a
GROUP BY '+@Parent_SKU+'';
PRINT(@SQL)
EXEC(@SQL)
SELECT *FROM ##TEMP_ParentsChild_Products;
答案 0 :(得分:2)
试试这个
SET @SQL = 'SELECT
a.'+@Parent_SKU+' AS ''Parent SKU''
,sum(case when '+@Child_SKU+' is null or '+@Child_SKU+' = '' then 0 else 1 end) AS ''ChildSKU_Total''
,STUFF((SELECT '','' +'+@Child_SKU+'
FROM ['+@TableName+'] b
WHERE b.'+@Parent_SKU+' = a.'+@Parent_SKU+'
AND b.'+@Child_SKU+' IS NOT NULL
FOR XML PATH('''')),1, 1, '''') AS ''ChildSKU''
INTO ##TEMP_ParentsChild_Products
FROM ['+@TableName+'] a
GROUP BY '+@Parent_SKU+'';
答案 1 :(得分:1)
将NULL连接到字符串时,结果为NULL。这也适用于许多其他SQL运算符。
所以你可以尝试使用ISNULL(@sku,'null')或类似的东西。
为什么必须动态构建?动态SQL很少是必需的,可能会带来安全风险。如果我是你,我会尝试使用参数化查询/存储过程。
答案 2 :(得分:1)
Child_SKU列中可能有NULL值,添加where条件如下,以避免空值和不必要的逗号。
SET @SQL = 'SELECT
a.'+@Parent_SKU+' AS ''Parent SKU''
,COUNT('+@Child_SKU+') AS ''ChildSKU_Total''
,STUFF((SELECT '','' +'+@Child_SKU+'
FROM ['+@TableName+'] b
WHERE b.'+@Parent_SKU+' = a.'+@Parent_SKU+'
AND b.'+@Child_SKU+' IS NOT NULL
FOR XML PATH('''')),1, 1, '''') AS ''ChildSKU''
INTO ##TEMP_ParentsChild_Products
FROM ['+@TableName+'] a
GROUP BY '+@Parent_SKU+'';