How to use variable in target database name for insert statement?

后端 未结 3 741
予麋鹿
予麋鹿 2021-01-23 11:09

I want to declare a server name and use this name in an insert statement. So far all i got is an error message.

declare @machine nvarchar(6);
declare @bar nvarch         


        
3条回答
  •  悲&欢浪女
    2021-01-23 11:41

    You will have to use dynamic sql for this. Try the following:

    declare @machine nvarchar(6);
    declare @bar nvarchar(3);
    declare @query nvarchar(4000)
    
    
    set @machine = 'Name00';
    set @bar = 'foo'
    
    set @query = 'insert into ' + @machine + '.dbname.dbo.table (column1, column2) select (column1, column2) from table where column1 = ''' + @bar + ''''
    
    execute dbo.sp_executesql @query
    

提交回复
热议问题