通过游标将primay键值插入另一个表

时间:2018-01-23 06:18:41

标签: sql sql-server database sql-server-2008 sql-server-2005

我在一个过程中有一个游标,用于获取表的主键 传递过程参数。我需要将主键的值插入另一个表

CREATE  PROCEDURE TRY25  @CURRENT_TABLE NVARCHAR(100)  

AS      

DECLARE @QUERY NVARCHAR(4000)   

SET NOCOUNT ON      
DECLARE     @COLUMNNAME AS NVARCHAR(MAX)    
DECLARE CURP CURSOR FOR    
SELECT COLUMN_NAME  FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS TC            
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS KU            
         ON TC.CONSTRAINT_TYPE = 'PRIMARY KEY' AND            
            TC.CONSTRAINT_NAME = KU.CONSTRAINT_NAME AND             
            KU.TABLE_NAME=@CURRENT_TABLE         
ORDER BY KU.TABLE_NAME, KU.ORDINAL_POSITION;      
OPEN CURP      
FETCH NEXT FROM CURP INTO @COLUMNNAME    
WHILE @@FETCH_STATUS = 0 BEGIN    
print concat(@columnname)  
FETCH NEXT FROM CURP INTO @COLUMNNAME    
END -- END OF FETCH    
CLOSE CURP    
DEALLOCATE CURP  

1 个答案:

答案 0 :(得分:1)

您需要使用动态SQL来执行此操作。下面是您可以使用的示例代码 -

    CREATE  PROCEDURE TRY25  @CURRENT_TABLE NVARCHAR(100)  

    AS      

    DECLARE @QUERY NVARCHAR(4000)   , @COLUMNList NVARCHAR(4000) 
    SET @COLUMNList = ''

    SET NOCOUNT ON      
    DECLARE     @COLUMNNAME AS NVARCHAR(MAX)    
    DECLARE CURP CURSOR FOR    
    SELECT COLUMN_NAME  FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS TC            
    INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS KU            
             ON TC.CONSTRAINT_TYPE = 'PRIMARY KEY' AND            
                TC.CONSTRAINT_NAME = KU.CONSTRAINT_NAME AND             
            KU.TABLE_NAME=@CURRENT_TABLE         
ORDER BY KU.TABLE_NAME, KU.ORDINAL_POSITION;      
OPEN CURP      
FETCH NEXT FROM CURP INTO @COLUMNNAME    
WHILE @@FETCH_STATUS = 0 BEGIN    

SET @COLUMNList = @COLUMNList + @columnname + ','

FETCH NEXT FROM CURP INTO @COLUMNNAME    
END -- END OF FETCH    
CLOSE CURP    
DEALLOCATE CURP

SET @COLUMNList  = SUBSTRING(@COLUMNList , 1 , LEN(@COLUMNList) -1)
SET @QUERY = 'INSERT INTO YOUR_DEST_TABLE SELECT ' + @COLUMNList + ' FROM '     + @CURRENT_TABLE  --CHANGE YOUR TABLE NAME
EXEC (@QUERY)
PRINT @QUERY