0

在一个表中有大约 113 列。表中有两条默认记录,一条为未知,一条为不适用。所以,每一列都有自己的默认值来表示未知和不适用。

我不想编写常规插入语句来获取这两条记录。

所以,我尝试使用游标插入每一列。

从 information_schema.columns 获取该表的列名,并尝试使用“insert into select”语句从另一个位置的确切表中插入值,但我们从 information_schema 获得的列名

Declare @col_name varchar(50)

declare my_cur CURSOR for
  select  column_name  from information_schema.columns 
  where table_name = 'tabl' and table_catalog = 'db'
  and table_schema = 'dbo'


  Fetch next from my_cur
  into @col_name

  while @@FETCH_STATUS  = 0
  BEGIN

   Insert into db.dbo.tabl (***@col_name***)
   select ***@col_name*** from openrowset('sqlncli', 'server=my_server;           trusted_connection=yes;', db.dbo.tabl) 



  fetch next from my_cur into @col_name
  end

close my_cur
deallocate my_cur
go

但是,我没有意识到 @col_name 会被视为字符串,而不是对象(列)

对于这种情况或任何替代解决方案是否有任何解决方法。

4

2 回答 2

5

I think that getting these defaults populated is the least of your problems.

I'd suggest taking a look at this: Fundamentals of Relational Database Design

And if you still want to do this, it might be better to retrieve all the defaults from the linked server, place them in a temp table, and then join to information_schema.columns to populate your table. You'll probably need to transpose the data to make it work.

于 2010-01-05T20:31:09.017 回答
1

You will have to generate the INSERT statement as dynamic SQL and then execute it

Declare @InsertStatement VarChar (Max)

SET @InsertStatement = ''

SET @InsertStatement = @InsertStatement + ' Insert into db.dbo.tabl (' + @col_name + ') '
SET @InsertStatement = @InsertStatement + ' select ' + @col_name + ' from openrowset(''sqlncli'', ''server=my_server'';  '

Exec Sp_SQLExec @InsertStatement
于 2010-01-05T20:29:26.417 回答