This is my SQL code.
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
The problem is I need to insert values to the table Basic
where ID
and GroupCode
will come from another table then column program
should have the value of the variable @tblnum
. And I don't know how to do that exactly. Kindly help. Thank you.
If I understand correctly, you can include it as a constant:
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;
You can also do it by passing the parameter to 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;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.