user2050600
user2050600

Reputation: 33

SQL Server procedure / function to copy table to another database

I need to copy a table from one database to another. My first guess was using following statement from my source code:

SELECT *  
INTO TARGETDB.SCHEMA.TABLENAME  
FROM SCHEMA.TABLENAME  

(Edit: I know it won't set Primary Key's etc, that's okay)

Sadly the classes I have to use in my project pretty much destroy this statement and I have no possibility to work around that.

My next idea was creating a function or procedure in the SQL Server database, so I could use

SCHEMA.FUNCTNAME paramTARGETDB, paramTABLENAME  

as statement from my code.

My current procedure looks like this:

CREATE PROCEDURE [SCHEMA].FUNCTNAME
    @pVC_TARGETDB VARCHAR(240),
    @pVC_TABLENAME VARCHAR(240)  
AS
BEGIN
  SELECT *
  INTO @pVC_TARGETDB.SYSADM.@pVC_TABLENAME
  FROM SCHEMA.@pVC_TABLENAME
END

but my knowledge of SQL isn't that big, and SQL Server Management Studio tells me there are syntax errors. Every @pVC_* is marked (Edit: In the first two occurances, they're not marked. Only in the block between BEGIN and END). The message I get is:

"Syntax Error near @pVC_* Expecting ID, QUOTED_ID or '.'."

I tried nearly every way of writing it I could imagine or find with Google, maybe it's easy to solve, maybe it's not. I couldn't do it, please help me.

Upvotes: 3

Views: 1559

Answers (1)

rufu5
rufu5

Reputation: 66

You can dynamically create the SQL statement then execute it

DECLARE @SQL NVARCHAR(MAX)

SET @SQL =
('SELECT *
INTO ' + @pVC_TARGETDB + '.SYSADM.' + @pVC_TABLENAME +
' FROM
SCHEMA.' + @pVC_TABLENAME)

EXEC (@SQL)

Upvotes: 2

Related Questions