这是我的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
中插入值,其中ID
和GroupCode
将来自另一个表,然后列program
应该具有变量的值@tblnum
。我不知道该怎么做。请帮助。谢谢。
答案 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;