I have this great function that parses a field into a pivot table consisting of four columns so I can sort my table accordingly. My only problem now is I can't use the function in a query that also calls a "text" datatype to be displayed in the results. Query runs fine as long as I don't include "spName" which is a "text" datatype. I've tried using cast and convert but neither built-in functions work in this query. thanks.
error:
Pivot grouping columns must be comparable. The type of column "spName" is "text", which is not comparable.
query:
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
sample data
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