从SELECT查询插入到

时间:2014-05-26 03:28:23

标签: sql sql-server

这是我的SQL代码。

CREATE TABLE [dbo].[Basic]
(
  ID int,
  GroupCode int,
  program int
)

DECLARE @tblnum int

SELECT tblnum FROM dbo.Program

SET @Qry = 'SELECT Hits_ID, GroupCode  FROM dbo.' + @tblnum 

INSERT INTO [dbo].[Basic]
(
ID,
GroupCode 
)
EXEC sp_executesql @Qry

问题是我需要在表Basic中插入值,其中IDGroupCode将来自另一个表,然后列program应该具有变量的值@tblnum。我不知道该怎么做。请帮助。谢谢。

1 个答案:

答案 0 :(得分:0)

如果我理解正确,您可以将其包含为常量:

CREATE TABLE [dbo].[Basic] (
  ID int,
  GroupCode int,
  program int
);

DECLARE @tblnum int;

SELECT tblnum FROM dbo.Program;

SET @Qry = 'SELECT Hits_ID, GroupCode, ''' + cast(@tblnum as varchar(255)) + ''' FROM dbo.' + @tblnum ;

INSERT INTO [dbo].[Basic](ID, GroupCode, program)
    EXEC sp_executesql @Qry;

您也可以将参数传递给sp_execute_sql

SET @Qry = 'SELECT Hits_ID, GroupCode, @tblnum FROM dbo.' + @tblnum ;

INSERT INTO [dbo].[Basic](ID, GroupCode, program)
    EXEC sp_executesql @Qry, N'@tblnum int', @tblnum = @tblnum;