How to get dynamically generated CREATE statement with SQL query? - sql-server

In MySQL you can do SELECT CREATE TABLE .... and it will return the CREATE statement that was used to create this table. I need to do the same in SQL Server.
Is there any similar functionality in SQL Server? I have a table name test_table.
I need to run a SELECT statement that would return the CREATE TABLE string that was used to create this table. I tried this but it didn't work. How can I achieve this result in SQL Server?

You could try SELECT INTO and specify the name of a temporary table (prefixed with #). It also works with physical tables (although I've not found a use for this). Something like this
select '123' as colName into #newTable;
select * from #newTable;
colName
123

Related

create table and assign table names from a select query in sqlite

I have a select query that returns a single column. Is there a way in sqlite to create a new table using the results as column names?
I tried this but it did not work.
CREATE TABLE newTable (SELECT nameCol FROM oldTable);
SQLite does not support dynamic SQL so this is not possible.
The best that you can do is construct the SQL statement that you can use to create the table by using your preferred programming language:
SELECT 'CREATE TABLE newTable (' ||
(SELECT GROUP_CONCAT(nameCol) FROM oldTable) ||
');' AS sql;
The above query returns 1 row with 1 column with a string like:
CREATE TABLE newTable (column1,column2,column3);
See a simplified demo.

Select into query, insert fails, but the table is created

I am using SQL Server 2016
I tried to the following query.
SELECT CONVERT(BIGINT, 'A') col1 INTO #tmp
This query is obviously in error. Because it does not convert.
However, the temporary table (#tmp) is created even if the query fails.
Why? I think this is by design, but I want to know.
P.S. PDW (parallel datawarehouse) does not create temporary table.

How to move the contents of a table in sql server to another with out using create

I'm trying to move a table in sql server to another table without the use of create. Is there any way to accomplish this.
I'm trying to use the select * from table
You can use SELECT . . INTO :
SELECT s.*
INTO <destination>
FROM <source> s;
This will create <DESTINATION> table with auto fill data.
Note : This will copy the table definition only includes (column/datatype).
Use simple insert query
insert into destination(columns)
select *
from source
where<condition>;
And delete existing record if you want
delete from source
where <condition>
commit;
The SELECT INTO statement creates a new table and inserts rows from the query into it.
Please refer this for more information.
SELECT
select_list
INTO
destination
FROM
source
[WHERE condition]

T-SQL table creation in source

I'm starting a new SQL Server Azure DB from scratch. I want to establish a strong source control so I want to be careful in how I create all my tables.
What is the best method to check if the table exists and only execute my CREATE TABLE statement if it does not exist yet? I'm working with passing dynamic SQL to a stored procedure that checks for the tables existence, but that is so limiting. There has to be a preferred way to do this out there. I mean I could preface every query with:
IF NOT EXISTS (SELECT *
FROM sys.objects
WHERE object_id = OBJECT_ID(N'[dbo].j[myTable]') AND type in(N'U'))
BEGIN
CREATE TABLE myTable(....)
END
But that's pretty repetitive.
More simply:
IF NOT EXISTS (SELECT * FROM sys.tables WHERE Name = N'myTable')
CREATE TABLE myTable .......
Idea: use the more focused sys.tables catalog view, instead of the all-encompassing sys.objects - then you don't have to remember those rather unintuitive type values..... - but yes, that is the safest way to do this kind of code.
As of SQL Server 2016, you can also use the
DROP TABLE IF EXISTS myTable;
CREATE TABLE myTable .......
command (which is new - see here: https://blogs.msdn.microsoft.com/sqlserverstorageengine/2015/11/03/drop-if-exists-new-thing-in-sql-server-2016/)

Use result of stored procedure to join to a table

I have a stored procedure that returns a dataset from a dynamic pivot query (meaning the pivot columns aren't know until run-time because they are driven by data).
The first column in this dataset is a product id. I want to join that product id with another product table that has all sorts of other columns that were created at design time.
So, I have a normal table with a product id column and I have a "dynamic" dataset that also has a product id column that I get from calling a stored procedure. How can I inner join those 2?
Dynamic SQL is very powerfull, but has some severe draw backs. One of them is exactly this: You cannot use its result in ad-hoc-SQL.
The only way to get the result of a SP into a table is, to create a table with a fitting schema and use the INSERT INTO NewTbl EXEC... syntax...
But there are other possibilities:
1) Use SELECT ... INTO ... FROM
Within your SP, when the dynamic SQL is executed, you could add INTO NewTbl to your select:
SELECT Col1, Col2, [...] INTO NewTbl FROM ...
This will create a table with the fitting schema automatically.
You might even hand in the name of the new table as a paramter - as it is dynamic SQL, but in this case it will be more difficult to handle the join outside (must be dynamic again).
If you need your SP to return the result, you just add SELECT * FROM NewTbl. This will return the same resultset as before.
Outside your SP you can join this table as any normal table...
BUT, there is a big BUT - ups - this sounds nasty somehow - This will fail, if the tabel exists...
So you have to drop it first, which can lead into deep troubles, if this is a multi-user application with possible concurrencies.
If not: Use IF EXISTS(SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME='NewTbl') DROP TABLE NewTbl;
If yes: Create the table with a name you pass in as parameter and do you external query dynamically with this name.
After this you can re-create this table using the SELECT ... INTO syntax...
2) Use XML
One advantage of XML is the fact, that any structure and any amount of data can be stuffed into one single column.
Let your SP return a table with one single XML column. You can - as you know the schema now - create a table and use INSERT INTO XmlTable EXEC ....
Knowing, that there will be a ProductID-element you can extract this value and create a 2-column-derived-table with the ID and the depending XML. This is easy to join.
Using wildcards in XQuery makes it possible to query XML data without knowing all the details...
3) This was my favourite: Don't use dynamic queries...

Resources