首先范圍是在 SQL Server 2000 兼容性中運行的資料庫
我有一個用于拆分字串的自定義函式
CREATE FUNCTION dbo.splitstring ( @stringToSplit VARCHAR(MAX) )
RETURNS
@returnList TABLE ([Name] [nvarchar] (500))
AS
BEGIN
DECLARE @name NVARCHAR(255)
DECLARE @pos INT
WHILE CHARINDEX(',', @stringToSplit) > 0
BEGIN
SELECT
@pos = CHARINDEX(',', @stringToSplit),
@name = SUBSTRING(@stringToSplit, 1, @pos-1)
INSERT INTO @returnList
SELECT ltrim(RTRIM(@name))
SELECT @stringToSplit = SUBSTRING(@stringToSplit, @pos 1, LEN(@stringToSplit) - @pos)
END
INSERT INTO @returnList
SELECT ltrim(RTRIM(@stringToSplit))
RETURN
END
它作業得很好。
現在我的問題
我有這個資料:

由以下 SQL 生成:
with CTE as
(
select '1' CustomerID, 'BCONS1' Code union
select '1', 'BCONS2' union
select '2' CustomerID, 'BCONS1' Code union
select '2', 'BCONS2'
)
select *
from CTE where CustomerID = 1
union
select Null, s.Name from dbo.splitstring('ACONS1,ACONS2,ACONS3') S
如何將“缺失”的 CustomerID 添加到我的結果中?
uj5u.com熱心網友回復:
您可以進行交叉應用,但 Compat 80 級也不支持。但是我們仍然可以強制兩個表的笛卡爾積:
with CTE as
(
select '1' CustomerID, 'BCONS1' Code union
select '1', 'BCONS2' union
select '2' CustomerID, 'BCONS1' Code union
select '2', 'BCONS2'
)
select *
from CTE where CustomerID = 1
union
select *
from
(select distinct
CustomerID,
s.Value
FROM CTE
, string_split('ACONS1,ACONS2,ACONS3', ',') S
where CustomerID = 1 -- restrict which rows you need to have added
) data
請注意,我在這里使用了 string_split 而不是您的函式,因為SEDE不允許我創建函式。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/415079.html
標籤:
上一篇:插入選擇和值
下一篇:檢索不同的客戶狀態
