gpt-3.5-turbo-0613· OpenAI
WildChat-4.8M (AI2)
in MS SQL, is it possible to create temp table with dynamic query?
- User
in MS SQL, is it possible to create temp table with dynamic query?
- Assistant
Yes, it is possible to create a temp table with a dynamic query in MS SQL. You can use the "EXEC" or "sp_executesql" statements to execute a dynamic SQL query and create a temp table within it.
Here is an example of creating a temp table with a dynamic query using the "EXEC" statement:
sqlDECLARE @tableName NVARCHAR(50) = '#TempTable'; DECLARE @sql NVARCHAR(MAX) = ' CREATE TABLE ' + @tableName + ' ( Id INT, Name NVARCHAR(50) ); INSERT INTO ' + @tableName + ' (Id, Name) SELECT Id, Name FROM YourTable WHERE ...; -- Your dynamic conditions SELECT * FROM ' + @tableName + ';'; EXEC(@sql);In this example, we're creating a temp table named "#TempTable" with columns "Id" and "Name". Then, we're inserting data from the "YourTable" table based on some dynamic conditions, and finally retrieving the data from the temp table.
Note that the temp table's name starts with a '#' symbol to denote that it is a temporary table.