Create table #info (id int,Sname varchar(50))
Create table #Post (Post_id int, id int,post varchar(50))
Create table #city (city_id int,id int,city varchar(100))
insert into #info(id,Sname) values(1,'sandip.')
insert into #info(id,Sname) values(2,'sandip_SP')
insert into #info(id,Sname) values(3,'sandip_Ak')
insert into #info(id,Sname) values(4,'sandip_Sk')
insert into #info(id,Sname) values(5,'sandipG')
insert into #Post(Post_id ,id,post) values(1,1,'Software Dev')
insert into #Post(Post_id ,id,post) values(2,2,'Database admin')
insert into #Post(Post_id ,id,post) values(3,3,'tester')
insert into #Post(Post_id ,id,post) values(4,4,'HR')
insert into #Post(Post_id ,id,post) values(5,5,'Team Lead')
insert into #city (city_id,id,city) values (1,1,'kolhapur')
insert into #city (city_id,id,city) values (1,1,'sangli')
insert into #city (city_id,id,city) values (1,1,'satara')
insert into #city (city_id,id,city) values (1,1,'karad')
insert into #city (city_id,id,city) values (1,1,'maharastra')
declare @main_str varchar(max)
declare @query_str varchar(max)
declare @InnerJoin_str varchar(max)
declare @Where_str varchar(max)
set @query_str =' select * from #temp a '
set @InnerJoin_str =' inner join #post b on a.id=b.id '
set @Where_str= 'Where a.id=4 '
set @main_str=''
set @main_str=@query_str+@InnerJoin_str+@Where_str
exec(@main_str)
--Add Dynamacally where clause in sql query
set @Where_str=@Where_str+ ' or b.post=''Software Dev'''
set @main_str=''
set @main_str=@query_str+@InnerJoin_str+@Where_str
exec(@main_str)
--Add Dynamacally joins in sql Query
set @InnerJoin_str=@InnerJoin_str+ ' inner join #city c on a.id=c.id '
set @main_str=''
set @main_str=@query_str+@InnerJoin_str+@Where_str
exec(@main_str)
link:
http://sandipgsql.blogspot.in/2013/05/dynamic-query-in-sql-server.html
0 comments:
Post a Comment