用光标插入语句

whi*_*net 0 t-sql sql-server cursor

在表格中有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
Run Code Online (Sandbox Code Playgroud)

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

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

Ale*_*use 5

我认为填充这些默认值是你的问题中最少的.

我建议看看这个:关系数据库设计的基础知识

如果您仍想这样做,最好从链接服务器检索所有默认值,将它们放在临时表中,然后连接到information_schema.columns以填充表.您可能需要转置数据才能使其正常工作.

  • 是的,那里有强烈的提示,113列的值与不相关的是一点设计FLAW (2认同)