x

How to auto create a table based on staging table?

I have staging table that are auto created when a new file is received. Now I need to create a table based on that staging table if it does not exist and load data.
more ▼

asked Aug 27, 2012 at 02:10 PM in Default

hope gravatar image

hope
50 4 4 5

(comments are locked)
10|1200 characters needed characters left

1 answer: sort voted first
--If the table does not exist, create it, based on the staging table
IF OBJECT_ID('SCHEMANAME.TABLENAME') IS NULL
  SELECT * FROM dbo.StagingTable INTO SCHEMANAME.TABLENAME WHERE 1=0

--Insert from the staging table
INSERT INTO SCHEMANAME.TABLENAME (<columnlist>) 
SELECT <columnlist> FROM dbo.StagingTable
Is that what you mean?
more ▼

answered Aug 27, 2012 at 08:02 PM

Magnus Ahlkvist gravatar image

Magnus Ahlkvist
16.6k 17 20 33

Thanks Magnus... I was trying something like that but I cant pass an error. My staging table comes from a variable and also the database table.

Like my script task creates a staging table and outputs two variables TableName (Database Table name) and StagingTable (Staging Table Name)

I used a sql task and used your code.

IF OBJECT_ID('@TableName') IS NULL SELECT * FROM @StagingTable INTO @TableName WHERE 1=0

And it gives the following error:

SSIS package "Package3.dtsx" starting. Error: 0xC002F210 at Execute SQL Task, Execute SQL Task: Executing the query "IF OBJECT_ID('@TableName') IS NULL SELECT * FROM..." failed with the following error: "Incorrect syntax near the keyword 'INTO'.". Possible failure reasons: Problems with the query, "ResultSet" property not set correctly, parameters not set correctly, or connection not established correctly. Task failed: Execute SQL Task SSIS package "Package3.dtsx" finished: Success. The program '[5804] Package3.dtsx: DTS' has exited with code 0 (0x0).

I know that i cannot use variables like this but can u suggest how can used them for creating the table.

Thanks
Aug 27, 2012 at 09:12 PM hope
slightly modify the query IF OBJECT_ID('dbo.TestTable') IS NULL SELECT * INTO dbo.TestTable FROM dbo.MainTable WHERE 1=0
Aug 31, 2012 at 02:01 PM yogirk
(comments are locked)
10|1200 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

New code box

There's a new way to format code on the site - the red speech bubble logo will automatically format T-SQL for you. The original code box is still there for XML, etc. More details here.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

SQL Server Central

Need long-form SQL discussion? SQLserverCentral.com is the place.

Topics:

x84

asked: Aug 27, 2012 at 02:10 PM

Seen: 885 times

Last Updated: Aug 31, 2012 at 02:01 PM