试试这个——
使用 LEFT JOIN 查询:
DECLARE
@s1 VARCHAR(50)
, @s2 VARCHAR(50)
SELECT
@s1 = '30:40:50'
, @s2 = '23,58,48,60'
SELECT
record_id = 104
, t2.id1
, t3.id2
, dt = CONVERT(VARCHAR(20), GETDATE(), 100)
FROM [master].dbo.spt_values t
LEFT JOIN (
SELECT
id1 = t.c.value('@s', 'INT')
, rn = ROW_NUMBER() OVER (ORDER BY 1/0)
FROM (
SELECT field = CAST('<t s = "' +
REPLACE(
@s1 + ':'
, ':'
, '" /><t s = "') + '" />' AS XML)
) d
CROSS APPLY field.nodes('/t') t(c)
WHERE t.c.value('@s', 'VARCHAR(5)') != ''
) t2 ON t.number = t2.rn
LEFT JOIN (
SELECT
id2 = t.c.value('@s', 'INT')
, rn = ROW_NUMBER() OVER (ORDER BY 1/0)
FROM (
SELECT field = CAST('<t s = "' +
REPLACE(
@s2 + ','
, ','
, '" /><t s = "') + '" />' AS XML)
) d
CROSS APPLY field.nodes('/t') t(c)
WHERE t.c.value('@s', 'VARCHAR(5)') != ''
) t3 ON t.number = t3.rn
WHERE (t2.id1 IS NOT NULL OR t3.id2 IS NOT NULL)
AND t.[type] = 'p'
使用 FULL OUTER JOIN 查询:
SELECT
record_id = 104
, t2.id1
, t3.id2
, dt = CONVERT(VARCHAR(20), GETDATE(), 100)
FROM (
SELECT
id1 = t.c.value('@s', 'INT')
, rn = ROW_NUMBER() OVER (ORDER BY 1/0)
FROM (
SELECT field = CAST('<t s = "' +
REPLACE(
@s1 + ':'
, ':'
, '" /><t s = "') + '" />' AS XML)
) d
CROSS APPLY field.nodes('/t') t(c)
WHERE t.c.value('@s', 'VARCHAR(5)') != ''
) t2
FULL OUTER JOIN (
SELECT
id2 = t.c.value('@s', 'INT')
, rn = ROW_NUMBER() OVER (ORDER BY 1/0)
FROM (
SELECT field = CAST('<t s = "' +
REPLACE(
@s2 + ','
, ','
, '" /><t s = "') + '" />' AS XML)
) d
CROSS APPLY field.nodes('/t') t(c)
WHERE t.c.value('@s', 'VARCHAR(5)') != ''
) t3 ON t2.rn = t3.rn
输出:
record_id id1 id2 dt
----------- ----------- ----------- --------------------
104 30 23 Jun 25 2013 3:50PM
104 40 58 Jun 25 2013 3:50PM
104 50 48 Jun 25 2013 3:50PM
104 NULL 60 Jun 25 2013 3:50PM