-3
declare @deb  nvarchar(200)
set @deb='raw'

insert into table11
select * from @deb.dbo.table2

The above code is not working. Is there any way to use server name as variable?

0

2 Answers 2

3

You cannot change a column, table, schema, or database reference in a SQL statement. On the other hand, you can use dynamic SQL:

declare @deb  nvarchar(200);
set @deb = 'raw';

declare @sql nvarchar(max);
set @sql = '
insert into table11
    select * from @deb.dbo.table2
';

set @sql  = replace(@sql, '@deb', @deb);

exec sp_executesql @sql;
Sign up to request clarification or add additional context in comments.

1 Comment

It is working but storing only one row.In table2 i have 152 records but randomly taking one row
2

Yes there is, Use Dynamic SQL

declare @deb  nvarchar(200)
set @deb='raw'

declare @sql as nvarchar(max) = 'insert into table11
select * from '+@deb+'.dbo.table2'

exec (@sql)

8 Comments

executing successfully but no records fetching.
no record fetching? it is suppose to insert all records from table2 into table1. Is it happening?
Sorry , only one record fetching.
Really? and you have multiple records in table?
in table2 i have 152 records, when ever i execute script the same record inserting in table. Means at a time only one record fetching , that too same record.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.