Friday, June 1, 2012
SQL Server With Syntax in Dynamic Query
Declare @sql nvarchar(max)
DEclare @tab nvarchar(50)
set @tab= 'Employeetable'
-- To get column list of table in database
select 'select * from '+@tab+' where ' + name + '=True' as query1 into Temptable
from sys.columns where object_id in(select object_id from sys.tables where name=''+@tab+'')
declare @colcount int
declare @counter int
DEclare @cmd nvarchar(max)
set @counter=0
select @colcount =COUNT(*) from Temptable
WHILE @counter < @colcount
BEGIN
SET @counter = @counter + 1
SET @cmd =';WITH MyCte AS ( select query1, RowNum = row_number() OVER ( order by query1 )
from Temptable ) SELECT query1 FROM MyCte WHERE RowNum = '+CONVERT(nvarchar,@counter)
EXECUTE sp_executesql @cmd
END
-- The above example is example for executing Dynamic Query Resultset
-- ;WITH MyCte AS ( select query1, RowNum = row_number() OVER ( order by query1 ) from Temptable )
--SELECT query1 FROM MyCte WHERE RowNum = 2
DECLARE @sqlCommand nvarchar(1000)
DECLARE @columnList varchar(75)
DECLARE @city varchar(75)
SET @columnList = 'EmpId, Salary, EmpName'
SET @city = 'Anu'
SET @sqlCommand = 'SELECT ' + @columnList + ',ROW_NUMBER() OVER( order by EmpId) as rownum
FROM Employee WHERE EmpName = @city'
EXECUTE sp_executesql @sqlCommand, N'@city nvarchar(75)', @city = @city
set @sqlCommand = 'SELECT *,ROW_NUMBER() OVER( order by query1) as rownum from Temptable'
EXECUTE sp_executesql @sqlCommand
Subscribe to:
Post Comments
(
Atom
)
No comments :
Post a Comment