我有这个很棒的功能,可以将一个字段解析为一个由四列组成的数据透视表,这样我就可以相应地对表进行排序。我现在唯一的问题是我不能在查询中使用该函数,该查询也调用“text”数据类型以显示在结果中。只要我不包含“spName”这是一个“text”数据类型,查询就可以正常运行。我尝试过使用强制转换和转换,但这个查询中都没有内置函数。感谢。
错误:
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
答案 0 :(得分:0)
不推荐使用Text
数据类型,并且在任何情况下,对于名称字段来说都是一个可疑的选择。
这对我有用
IF OBJECT_ID('tempdb..#TestTable') IS NULL
BEGIN
CREATE TABLE #TestTable
(
recid INT PRIMARY KEY,
title VARCHAR(50),
spName TEXT
)
INSERT INTO #TestTable
SELECT 1 AS recid, 'QW 1 RT 309-23-1' AS title, CAST('test1' AS TEXT) AS spName UNION ALL
SELECT 2 AS recid, 'QW 1 RT 29-1', CAST('test' AS TEXT) AS spName UNION ALL
SELECT 3 AS recid, 'QW 1 RT 750-1', CAST('test' AS TEXT) AS spName UNION ALL
SELECT 4 AS recid, 'QW RT 750-1' , CAST('test' AS TEXT) AS spName
END
SELECT recid, title, spName, [1] AS [COLUMN 1], [2] AS [COLUMN 2],[3] AS [COLUMN 3],[4] AS [COLUMN 4]
FROM
(SELECT recid, title, CAST(spName AS VARCHAR(MAX)) AS spName FROM #TestTable ) T
CROSS APPLY dbo.GetNumbers(title)
PIVOT
(MAX(num) FOR idx IN ([1], [2],[3],[4])
) AS PivotTable;