WRITE A FUNCTION TO DISPLAY THE OUTPUT OF AN EXISTING TABLE
RANGE LIKE COMMAM SEPERATED VALUES LIKE RANGE1,RANGE2,...

Answer Posted / jk.garg25

you can write this query in table valued function

DECLARE @RangeValue As VARCHAR(MAX)
SET @RangeValue = '1,2,'

DECLARE @Qry As VARCHAR(MAX)

DECLARE @ResData AS VARCHAR(MAX)
DECLARE @InData AS VARCHAR(MAX)

DECLARE @rId AS INT
DECLARE @Pos AS INT

SET @ResData = ''
SET @InData = ''
WHILE(LEN(@RangeValue)>1)
BEGIN
SET @Pos = CHARINDEX(',',@RangeValue,1)
SET @rId = SUBSTRING(@RangeValue,1,@Pos-1)
SET @ResData = @ResData + CASE WHEN @ResData <> '' THEN ','
ELSE '' END + 'ISNULL(['+ CAST(@rId AS VARCHAR(5)) + '],0)
AS Range' + CAST(@rId AS VARCHAR(5))
SET @InData = @InData + CASE WHEN @InData <> '' THEN ','
ELSE '' END + '['+ CAST(@rId AS VARCHAR(5)) + ']'
SET @RangeValue=SUBSTRING(@RangeValue,@Pos+1,LEN(@RangeValue))
END

SET @Qry =
'SELECT '
+ @ResData +
' FROM
(
SELECT Col1 FROM table1(NoLock)
) p
PIVOT
(
MAX (Col1) FOR Col1 IN (' + @InData + ')
) AS pvt'

--PRINT (@Qry)
EXEC (@Qry)

Is This Answer Correct ?    1 Yes 0 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

Differentiate between mongodb vs. Sql server?

675


What is command parameter in ssrs?

130


What is nonclustered index on computed columns?

646


What is cursors? And what are the different types of cursor?

649


List all the types of user-defined functions?

596






What method is used by the Command classes to execute SQL statements that return single values?

676


Relational calculus is what type of language?

674


What is the difference between drop table and truncate table?

566


What are the triggers in sql?

656


What is a scheduled job or what is a scheduled task?

618


What is the contrast amongst drop and truncate?

638


How to rename an existing table with the "sp_rename" stored procedure in ms sql server?

636


What is a database in ms sql server?

638


What does sql server mean?

612


How to enter comments in transact-sql statements?

642