WRITE A FUNCTION TO DISPLAY THE OUTPUT OF AN EXISTING TABLE
RANGE LIKE COMMAM SEPERATED VALUES LIKE RANGE1,RANGE2,...
Answers were Sorted based on User's Feedback
Answer / carmel franco
Create function int select_dynamic(range varchar(255))
As
declare
@Qry Varchar(2000)
Begin
Begin try
Set @Qry =”select * from table1 where col1
in (“+range+”)”
Exec @qry
Catch
Print “error processing parameter”
Return -1
End try
Return 1
END
Is This Answer Correct ? | 2 Yes | 0 No |
Answer / 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 |
How to avoid cursors?
3 Answers CarrizalSoft Technologies, HP,
In what version of sql server were synonyms released?
Define tempdb database?
What are the advantages of mirroring?
What do you understand by check constraint in sql server?
CREATE TABLE [dbo].[HPMS_CompetencyTypes](CompetencyType varchar(50) ) go create trigger hpms_create_Insert on HPMS_CompetencyTypes for insert as if Exists ( select * from [HPMS_CompetencyTypes] where CompetencyType=(select * from [HPMS_CompetencyTypes])) begin Rollback tran Raiserror ('duplicate value',12,6) go insert HPMS_CompetencyTypes (CompetencyType) values ('new') I'm new to trigger can any one tell me where is the issue. Please.
how can you find out if the current user is a member of the specified microsoft® windows nt® group or microsoft sql server™ role? : Sql server administration
How to select some specific columns from a table in a query in ms sql server?
What is scalar user-defined function?
Explain syntax for dropping triggers?
Is it possible to create a stored procedure that runs a query and outputs the results to a text file and allows me to add extra delimeters and static field info. If so How?
what are the different types of replication you can set up in sql server? : Sql server database administration