1
我遇到了一個失敗的表值函數的連接,我無法解釋它。我在下面創建了一個測試腳本,我在SQL Server 2008 R2上運行這個腳本加入到表值函數失敗
任何人都可以理解爲什麼在測試腳本結束時第一個SELECT語句有效,第二個語句不起作用?
CREATE TABLE dbo.Test (Setting INT NOT NULL, Value NVARCHAR(MAX) NULL)
GO
INSERT dbo.Test (Setting, Value)
SELECT 3151, '2~-10011;2~-10012'
GO
CREATE FUNCTION [dbo].[CTESplitChunk] (@list nvarchar(MAX),
@delim nchar(1) = ',')
RETURNS @t TABLE (str nvarchar(4000) NOT NULL) AS
BEGIN
DECLARE @slice nvarchar(4000),
@textpos int,
@maxlen int,
@stoppos int,
@lastone bit
SELECT @textpos = 1, @maxlen = 4000 - 2, @lastone = 0
WHILE @lastone = 0
BEGIN
IF datalength(@list)/2 - (@textpos - 1) >= @maxlen
BEGIN
SELECT @slice = substring(@list, @textpos, @maxlen)
SELECT @stoppos = @maxlen -
charindex(@delim COLLATE Slovenian_BIN2, reverse(@slice))
SELECT @slice = left(@slice, @stoppos) + @delim
SELECT @textpos = @textpos - 1 + @stoppos + 2 -- On the other side of the comma.
END
ELSE
SELECT @slice = substring(@list, @textpos, @maxlen) + @delim,
@lastone = 1
;WITH csvtbl(start, stop) AS (
SELECT start = 1,
stop = charindex(@delim COLLATE Slovenian_BIN2, @slice)
UNION ALL
SELECT start = stop + 1,
stop = charindex(@delim COLLATE Slovenian_BIN2,
@slice, stop + 1)
FROM csvtbl
WHERE stop > 0
)
INSERT @t (str)
SELECT ltrim(rtrim(
substring(@slice, start,
CASE WHEN stop > 0 THEN stop - start ELSE 0 END)))
FROM csvtbl
WHERE stop > 0
OPTION (MAXRECURSION 0)
END
RETURN
END
GO
SELECT Value
FROM dbo.Test t
WHERE t.Setting = '3151'
GO
SELECT Value
FROM dbo.Test t
INNER JOIN dbo.CTESplitChunk (t.Value, ';') s ON 1 = 1
WHERE t.Setting = '3151'
是的,謝謝 - 發佈後,我明白了!學校男孩錯誤:-) – Drammy
現在你已經在代碼中加入了'CROSS APPLY'這個回答看起來很奇怪。關於爲什麼加入一些可以根據't.Value'改變其內容的表表達式是沒有意義的。內連接應該是可交換的。你怎麼能從TVF開始加入? –
理解 - 我補充說,在我看到您的答案之前 - 我將刪除編輯以備將來參考。 – Drammy