0

I would like to auto create a table using BIDS. How would I go about auto-making a new table when the data structure is unknown?

example in SQL I would do:

SELECT * INTO <NEW_TABLE> FROM <ORIGINAL_TABLE>

However, I get the data set. Transform it and want to create a table without knowing the structure.

Is there a way to do that?

ldav1s
  • 15,885
  • 2
  • 53
  • 56

1 Answers1

0

You can define the metadata for a table based on the results of a query, sort of. Some things like an identity property, unique constraint, defaults, primary key, etc will not be able to be determined but if you just want column names and data types but no data, then what you have is essentially what you need

SELECT *
INTO
    <NEW_TABLE>
FROM
    <ORIGINAL_TABLEs and/or many joins>
WHERE
    NULL = NULL

The where clause is the trick. Just use a condition that will never be true. The query will evaluate, you'll get all the column names that are defined and their types but no data will be populated in the new table.

You might be interested in wrapping this with an existence check. Either drop the table if it exists or don't create it if it already exists. I'm not sure what would be appropriate in your situation but the check would be

IF EXISTS (SELECT * FROM sys.tables T WHERE T.name = N'MyTable' AND T.schema_id = SCHEMA_ID('mySchema'))
BEGIN
    -- Take action here as the table exists (or not)
END
billinkc
  • 59,250
  • 9
  • 102
  • 159