March 31, 2022 at 3:29 pm
Is it possible to create a temp table when setting a query?
For example:
DECLARE
@Category varchar(100),
@SubCategory varchar(100),
@Query varchar(1000)
SET @Query = 'SELECT TestName FROM tblTest WHERE CategoryID = (CategoryID =' + @CategoryID + ') AND (SubCategory IN (' + @SubCategory + '))'
EXEC(@Query)
How could I place the results into a temp table?
Many thanks in advance.
March 31, 2022 at 4:08 pm
Here's an example
DECLARE @Query VARCHAR(1000) = 'SELECT TOP (10) object_id, name FROM sys.columns';
DROP TABLE IF EXISTS #SomeTab;
CREATE TABLE #SomeTab
(
object_id INT
,name NVARCHAR(128)
);
INSERT #SomeTab
(
object_id
,name
)
EXEC (@Query);
SELECT *
FROM #SomeTab st;
April 1, 2022 at 3:19 pm
Is it possible to create a temp table when setting a query?
For example:
DECLARE
@Category varchar(100),
@SubCategory varchar(100),
@Query varchar(1000)
SET @Query = 'SELECT TestName FROM tblTest WHERE CategoryID = (CategoryID =' + @CategoryID + ') AND (SubCategory IN (' + @SubCategory + '))'
EXEC(@Query)How could I place the results into a temp table?
Many thanks in advance.
I see no reason to use Dynamic SQL in this case. In fact, what you've posted is actually dangerous code because it concatenates user character based variables into the dynamic SQL making it extremely susceptible to SQL-Injection.
Yep... I do realize it's "just" and example but other readers need to be warned and maybe you do to because I find that most examples are born from the limits of what someone knows.
--Jeff Moden
Change is inevitable... Change for the better is not.
Viewing 3 posts - 1 through 3 (of 3 total)
You must be logged in to reply to this topic. Login to reply
This website stores cookies on your computer.
These cookies are used to improve your website experience and provide more personalized services to you, both on this website and through other media.
To find out more about the cookies we use, see our Privacy Policy