使用XML过滤SQL结果

时间:2019-01-29 12:15:43

标签: sql xml tsql

我创建了以下代码,以确保可以使用逗号分隔的参数来过滤某些尺寸:

DECLARE @Dimension NVARCHAR(MAX)

SET @Dimension = 'Average Life,Coupon Frequency'

DECLARE @XML XML
SET @XML = CAST('<i>' + REPLACE(@Dimension, ',', '</i><i>') + '</i>' AS XML)

SELECT d.* 
FROM Dim_Security_Analytics as d

INNER JOIN @XML.nodes('i') x(i) 
    ON  d.dimension = x.i.value('.', 'NVARCHAR(MAX)')

WHERE d.Date = '2018-12-31'

但是,当在@Dimension参数中传递''或NULL时,我希望返回所有尺寸。我不确定如何在XML中对此进行编码,因为这对我来说是很新的。

有人能指出我正确的方向吗?

谢谢

2 个答案:

答案 0 :(得分:0)

您可以简单地使用STRING_SPLIT(需要SQL Server 2016或更高版本):

DECLARE @Dimension NVARCHAR(100) = 'Average Life,Coupon Frequency';

SELECT *
FROM Dim_Security_Analytics
WHERE Date = '2018-12-31'
AND (@Dimension IS NULL OR dimension IN (
    SELECT value FROM STRING_SPLIT(@Dimension, ',')
))

答案 1 :(得分:0)

您可以尝试以下方法:

DECLARE @Dimension NVARCHAR(MAX)

SET @Dimension = 'Average Life,Coupon Frequency'

DECLARE @XML XML
SET @XML = CAST('<i>' + REPLACE(@Dimension, ',', '</i><i>') + '</i>' AS XML)

DECLARE @mockup TABLE(ID INT IDENTITY,SomeValue VARCHAR(100), dimension NVARCHAR(MAX),[Date] DATE);
INSERT INTO @mockup VALUES('First row','missing dimension','2018-12-31')
                         ,('second row','Average Life','2018-12-31')
                         ,('third row','Coupon Frequency','2018-12-31')
                         ,('fourth row',NULL,'2018-12-31');

SELECT d.* 
FROM @mockup as d
WHERE d.Date = '2018-12-31' 
  AND (@Dimension IS NULL OR LEN(@Dimension) = 0 OR @XML.exist('/i[text()=sql:column("dimension")]')=1);

我们将逻辑从INNER JOIN转移到WHERE

使用声明的表变量(在XML中填充而不是直接使用XML)可能会更快。