Hi there,
In a query, imagine you need to get the values separated by commas in a dynamic column where you have sometimes four, five or six values.
Let me show you:
--declare @core_value varchar(200) = 'microwave,oven,dish_washer,refrigerated,pressure_cooker,steamer'; declare @core_value varchar(200) = 'microwave,oven,dish_washer,refrigerated'; --getting the number of commas plus 1 in order to know in advance how many values need to split out SELECT (LEN(@core_value) - LEN(REPLACE(@core_value, ',', ''))) + 1 as Number_of_Times SELECT dbo.GetColumnValue(@core_value, ',', 1) as Product_Support_Devices1 ,dbo.GetColumnValue(@core_value, ',', 2) as Product_Support_Devices2 ,dbo.GetColumnValue(@core_value, ',', 3) as Product_Support_Devices3 ,dbo.GetColumnValue(@core_value, ',', 4) as Product_Support_Devices4 ,dbo.GetColumnValue(@core_value, ',', 5) as Product_Support_Devices5 ,dbo.GetColumnValue(@core_value, ',', 6) as Product_Support_Devices6
If you run the above query you will get "Product_Support_Devices5" and "Product_Support_Devices6" with fake values, in fact they don't exist, however the UDF (below) extract a value not a NULL
UDF am I using:
CREATE FUNCTION dbo.GetColumnValue( @String VARCHAR(MAX), @Delimiter CHAR(1), @Column INT = 1 ) RETURNS VARCHAR(MAX) AS BEGIN DECLARE @idx INT DECLARE @slice VARChar(MAX) SELECT @idx = 1 IF LEN(@String)<1 OR @String IS NULL RETURN NULL DECLARE @ColCnt INT SET @ColCnt = 1 WHILE (@idx != 0) BEGIN SET @idx = CHARINDEX(@Delimiter,@String) IF @idx!=0 BEGIN IF (@ColCnt = @Column) RETURN LEFT(@String,@idx - 1) SET @ColCnt = @ColCnt + 1 END SET @String = RIGHT(@String,LEN(@String) - @idx) IF LEN(@String) = 0 BREAK END RETURN @String END
So the idea is getting real values not repeated ones
Thanks for your inputs/hints
Enric