Quantcast
Channel: Transact-SQL forum
Viewing all articles
Browse latest Browse all 23857

How to pass the value through variable in dynamic query in sql

$
0
0

Hi,

i have written below query for dynamically create the table and insert the records from source table.

                                   
Declare @Sql Varchar(Max)
Declare @x int
declare @value varchar(100),@schema varchar(100)='aaa'
Declare @f1 Varchar(100)
Declare @table Table(Idt Int Identity(1,1),grp_id numeric(18,0),id int)
Insert Into @table Select Distinct grp_id,0 from abc..table1
Select @x = Max(Idt) from @table
select @value=(select id from cde..table2 where Shortname='+@schema+')
While @x>0
Begin
Select @f1= grp_id From @table Where Idt = @x
Set @Sql =
'If Exists( Select 1 from sys.objects where name = ''condition_'+@f1+''' And Type_Desc = ''USER_TABLE'')

Insert Into condition_'+@f1+ ' Select * from abc..table1
Where grp_id = '''+@f1+'''

Else

Select * Into condition_'+@f1+' from abc..table1
Where grp_id = '''+@f1+'''
alter table condition_'+@f1+' add id int
update condition_'+@f1+' set id = '+@value+'
'
 Set @x = @x-1
 --print @sql
 Exec (@Sql)
End

how to pass the table name , database name through variable for this query because this query is used for 5 tables so every time change the table name. 

so will use the variable and pass the value for table name and database name only.

please modify this query.

Regards,

Abdul Khadir.



Viewing all articles
Browse latest Browse all 23857

Trending Articles