我有一个方案,其中我需要查询SSRS报告的值,并将它们分别以单独的状态显示并全部串联在一起。为避免将来对SSRS报告进行更改,我希望在查询中进行串联。但是,由于重复了对CONCAT()函数内部各列执行的操作,因此我当前的查询有很多冗余代码:
remote_table
作为SQL的新手,我尝试将列的别名传递到CONCAT()函数中,但无济于事。
虽然此查询确实实现了我想要的功能,但我想知道是否可以清理或重组它以避免此类冗余代码。
答案 0 :(得分:2)
使用CTE是处理此类问题的最简单方法。像这样的东西。
with MyData as
(
SELECT
CASE
WHEN a.TwoPartColumn LIKE '%-%'
THEN LEFT(a.TwoPartColumn, CHARINDEX('-', a.TwoPartColumn) - 1)
ELSE a.TwoPartColumn
END AS FirstPart,
CASE
WHEN a.TwoPartColumn LIKE '%-%'
THEN RIGHT(a.TwoPartColumn, LEN(a.TwoPartColumn) - CHARINDEX('-', a.TwoPartColumn))
ELSE '001'
END AS SecondPart,
LEFT(rtrim(b.RightPadThis) + '0000000000', 10) AS RightPadded,
RIGHT('00000000'+ rtrim(b.LeftPadThis,0), 8) AS LeftPadded,
b.Units AS Units
FROM TableA AS a
JOIN TableB AS b ON b.Id = a.Id
WHERE b.Param = @Param
)
select FirstPart
, SecondPart
, RightPadded
, LeftPadded
, Units
, concat(FirstPart, SecondPart, RightPadded, LeftPadded, Units)
from MyData
答案 1 :(得分:1)
使用交叉申请:
SELECT
part.FirstPart,
part.SecondPart,
LEFT(rtrim(b.RightPadThis) + '0000000000', 10) AS RightPadded,
RIGHT('00000000'+ rtrim(b.LeftPadThis,0), 8) AS LeftPadded,
b.Units AS Units,
CONCAT
(
part.FirstPart,part.SecondPart,
LEFT(rtrim(b.ItemCd) + '0000000000', 10),
RIGHT('00000000'+ rtrim(b.LeftPadThis,0))), 8),
b.Units
) AS Concatenated
FROM TableA AS a
JOIN TableB AS b ON b.Id = a.Id
CROSS APPLY (
SELECT CASE
WHEN a.TwoPartColumn LIKE '%-%'
THEN LEFT(a.TwoPartColumn, CHARINDEX('-', a.TwoPartColumn) - 1)
ELSE a.TwoPartColumn
END AS FirstPart,
CASE
WHEN a.TwoPartColumn LIKE '%-%'
THEN RIGHT(a.TwoPartColumn, LEN(a.TwoPartColumn) - CHARINDEX('-', a.TwoPartColumn))
ELSE '001'
END AS SecondPart) part
)
WHERE b.Param = @Param
您可以对其他重复表达使用相同的技术