How to make this declaration reusable on Dynamic Query?
I got this query as a part of our long stored procedure that we have.
As you can see, we declare the table so we can reuse this for the query within the same procedure.How to make this dynamic?
Cause in my case the table oflime_survey_XXX
is dynamic depending on the the variable that you passed.
Now ... I can include this DECLARE @lime_survey_generic
as a part of the string of query but then I want to be able to reuse this table for query later on within the same stored procedure.
DECLARE @lime_survey_generic TABLE
(
id INT,
submitdate DATETIME,
lastpage INT,
startlanguage VARCHAR(20),
token VARCHAR(36),
datestamp DATETI开发者_StackOverflow中文版ME,
startdate DATETIME,
ipaddr TEXT,
refurl TEXT,
Q010101 VARCHAR(5),
Q010102 VARCHAR(5),
Q010103 TEXT,
Q010201 VARCHAR(5),
Q010202 VARCHAR(5),
Q010203 TEXT,
Q010301 VARCHAR(5),
Q010302 VARCHAR(5),
Q010303 TEXT,
Q010401 VARCHAR(5),
Q010402 VARCHAR(5),
Q010403 TEXT,
Q010501 VARCHAR(5),
Q010502 VARCHAR(5),
Q010503 TEXT,
Q010601 VARCHAR(5),
Q010602 VARCHAR(5),
Q010603 TEXT,
Q010701 VARCHAR(5),
Q010702 VARCHAR(5),
Q010703 TEXT,
Q010801 VARCHAR(5),
Q010802 VARCHAR(5),
Q010803 TEXT,
Q010901 VARCHAR(5),
Q010902 VARCHAR(5),
Q010903 TEXT,
Q011001 VARCHAR(5),
Q011002 VARCHAR(5),
Q011003 TEXT,
Q011101 VARCHAR(5),
Q011102 VARCHAR(5),
Q011103 TEXT,
Q011201 VARCHAR(5),
Q011202 VARCHAR(5),
Q011203 TEXT,
Q011301 VARCHAR(5),
Q011301Other TEXT
);
DECLARE @SQL NVARCHAR(128);
SET @SQL = N'INSERT INTO ' + @lime_survey_generic + ' ' +
'SELECT * FROM lime_survey_' + CAST(@SurveyID AS VARCHAR)
EXECUTE sp_executesql @SQL
Maybe like this:
DECLARE @lime_survey_generic TABLE
(
id INT,
submitdate DATETIME,
lastpage INT,
startlanguage VARCHAR(20),
token VARCHAR(36),
datestamp DATETIME,
startdate DATETIME,
ipaddr TEXT,
refurl TEXT,
Q010101 VARCHAR(5), Q010102 VARCHAR(5), Q010103 TEXT,
Q010201 VARCHAR(5), Q010202 VARCHAR(5), Q010203 TEXT,
Q010301 VARCHAR(5), Q010302 VARCHAR(5), Q010303 TEXT,
Q010401 VARCHAR(5), Q010402 VARCHAR(5), Q010403 TEXT,
Q010501 VARCHAR(5), Q010502 VARCHAR(5), Q010503 TEXT,
Q010601 VARCHAR(5), Q010602 VARCHAR(5), Q010603 TEXT,
Q010701 VARCHAR(5), Q010702 VARCHAR(5), Q010703 TEXT,
Q010801 VARCHAR(5), Q010802 VARCHAR(5), Q010803 TEXT,
Q010901 VARCHAR(5), Q010902 VARCHAR(5), Q010903 TEXT,
Q011001 VARCHAR(5), Q011002 VARCHAR(5), Q011003 TEXT,
Q011101 VARCHAR(5), Q011102 VARCHAR(5), Q011103 TEXT,
Q011201 VARCHAR(5), Q011202 VARCHAR(5), Q011203 TEXT,
Q011301 VARCHAR(5), Q011301Other TEXT
);
DECLARE @SQL NVARCHAR(128);
SET @SQL = N'SELECT * FROM lime_survey_' + CAST(@SurveyID AS VARCHAR);
INSERT INTO @lime_survey_generic
EXECUTE sp_executesql @SQL;
?
精彩评论