我有这个很棒的功能,可以将一个字段解析为一个由四列组成的数据透视表,这样我就可以对我的表进行相应的排序。我现在唯一的问题是我不能在查询中使用该函数,该函数还调用“文本”数据类型以显示在结果中。只要我不包含作为“文本”数据类型的“spName”,查询就可以正常运行。我尝试过使用cast 和 convert,但是在这个查询中内置函数都不起作用。谢谢。
错误:
Pivot grouping columns must be comparable. The type of column "spName" is "text", which is not comparable.
询问:
SELECT title, recID, spName, [1] AS [Col1], [2] AS [Col2],[3] AS [Col3],[4] AS [Col4]
FROM (select title, recID, spName from TestTable) t CROSS APPLY dbo.GetNumbers(title) PIVOT (MAX(num) FOR idx IN ([1], [2],[3],[4]) ) AS PivotTable ORDER BY Col1
udf:
CREATE FUNCTION GetNumbers
(
@Numbers NVARCHAR(2000)
)
RETURNS @Results TABLE
(
idx INT IDENTITY(1,1),
num INT
)
AS
BEGIN
DECLARE @NonNumericIndex INT, @NumericIndex INT
SET @NumericIndex = PATINDEX('%[0-9]%',@Numbers)
IF (@NumericIndex > 4) --First Column not there
INSERT INTO @Results VALUES (NULL)
WHILE @NumericIndex > 0
BEGIN
SET @Numbers = RIGHT(@Numbers,LEN(@Numbers)-@NumericIndex+1)
SET @NonNumericIndex = PATINDEX('%[^0-9]%',@Numbers)
IF(@NonNumericIndex = 0)
BEGIN
INSERT
INTO @Results VALUES (@Numbers)
RETURN
END
ELSE
INSERT
INTO @Results VALUES
(LEFT(@Numbers,@NonNumericIndex-1))
SET @Numbers = RIGHT(@Numbers,LEN(@Numbers)-@NonNumericIndex+1)
SET @NumericIndex = PATINDEX('%[0-9]%',@Numbers)
END
RETURN
END
样本数据
title recid spname
QW 1 RT 309-23-1 1 This is title 1 words
QW 1 RT 29-1 2 this is title 2 desc
QW 1 RT 750-1 3 This is title 3
QW RT 750-1 4 This is title 4 words