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
What happens when transaction log is full?
How to modify the underlying query of an existing view?
Which autogrowth database setting is good?
What command would you use to create an index?
What is the main purpose of having conversation group?
Are there any preferred steps that need to be taken care of before starting the installation of sql server 2000?
What is a join in sql? What are the types of joins?
What is the difference between substr and charindex in the sql server?
What stored by the model?
What stored by the master? : sql server database administration
you have separate development and production systems you want to move a copy of a development database into production to do this, you do a backup on the development system and restore to the production system after a few minutes, you begin getting calls from several customers saying that they are denied access to the system why? : Sql server administration
What does man by sql wildcard characters in sql server?
Why are you getting errors when creating a new odbc dsn?
What action plan is preferred if sql server is not responding?
What is read uncmmited?