Most of the cases, our requirements will be dynamic. Sometimes, the person will request for one column to be fetched from the database, may be two columns. The decisions will be taken at run time.
I used to face a requirement to fetch the data based on the login user. userA needs 5 columns and userB needs 2 columns.
I need to have a common code to satisfy both the requirement. Such kind of scenario can be handled using dynamic SQL.
Query will be generated at the run time and it will be executed to fetch the result. The dynamically created query will be executed by a special system stored procedure namely sp_executeSQL. Let's see a small code snippet on this.
-- Creating a table named venkatTable
drop table venkatTable
create table venkatTable(id int identity(1,1) primary key, nam varchar(100))
insert into venkatTable values('Venkatesan Prabu')
insert into venkatTable values('Subashini')
insert into venkatTable values('Jayakantham')
insert into venkatTable values('Arunachalam')
insert into venkatTable values('Santhi')
select * from venkattable
-- Am declaring three variables @val3 will be a query created.
-- It should be executed dynamically using sp_executesql
declare @val1 varchar(100)
declare @val2 varchar(100)
declare @val3 nvarchar(100)
set @val1 ='id'
set @val2='nam'
set @val3= 'select '+ @val1 + ','+ @val2 + ' from venkattable'
print @val3
exec sp_executesql @val3
Thanks and Regards,
Venkatesan Prabu .J