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 can sql injection be stopped? : sql server security
What are the differences between having and where clause.
What is the maximum number of instances in 32 bit and 64 bit sql server 2012?
Suppose you want to implement the many-to-many relationships while designing tables. How would you do it?
Can you explain full-text query in sql server?
How do I find information about the install locations for the various instances running on a computer?
Do you know data definition language, data control language and data manipulation language?
What is difference between primary key and foreign key?
What the different components of Replication and what is their use?
when would you go for denormalization? : Sql server database administration
Write a program using SQL queries to find a unique entry in a table.
If user is owning any SQL Objects, can we drop that user
Explain about link server in sql server?
What is the difference between varchar and nvarchar?
What are the authentication modes in sql server? How can it be changed?