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
How to provide column names in insert statements in ms sql server?
How to call a function from a stored procedure in SQL Server ?
How many database files are there in sql server 2000?what are they?
what changed between the previous version of sql server and the current version? : Sql server database administration
What is open database communication (odbc)?
what is an extended stored procedure? Can you instantiate a com object by using t-sql? : Sql server database administration
What are the requirements for sql server 2016?
If a stored procedure is taking a table data type, how it looks?
Why olap is used?
What is use of except clause?
Which operator do you use to return all of the rows from one query except rows are returned in a second query?
How to find the version of sql server? : sql server database administration
What is truncate table?
When should you use an instead of trigger?
You want to use bids to deploy a report to a different server than the one you chose in the report wizard. How can you change the server url?