0

I have a weird SQL situation in which I need to create a SQL script that I would run against database A and it would output another SQL script that would contain INSERT statements which I can then run against database B and upload the data (essentially an Export from A to B but a longer way).

I was wondering if anyone has worked on this an can suggest a way to generate INSERT statements that would contain data from [Database A].[Table Student] which can then be uploaded to [Database B].[Table Student].

Thanks a lot.

1
  • Depending on the version, there are easier ways. For example you could export a .dacpac Commented Nov 6, 2017 at 11:07

4 Answers 4

1

You can concat the values from student into an insert string like:

SELECT concat('Insert INTO Students VALUES(', Col1,', ', '''', Col2, '''', ')')
     AS [Details]
     FROM Student
     WHERE ...

N.B The four single quotes is to create a single quote before and after varchar columns for example.

To generate a new SQL script from this, I'd create a cmd file with something like:

SET SERVER=YOUR_SERVER
SET DATABASE=YOUR_DB

sqlcmd -S %SERVER% -d %DATABASE% -h -1 -i Script.sql -o NewScript.sql -W
Sign up to request clarification or add additional context in comments.

1 Comment

This is just what I needed...Thanks a lot for your help.
0

-- You Can Simple Use insert into statement

INSERT INTO [Database B].[Table Student]
SELECT * FROM [Database A].[Table Student] 
WHERE StudentID NOT IN (SELECT  StudentID FROM  [Database B].[Table Student])

Comments

0

Here is one way that would insert data from one database table to other database table

INSERT INTO [DestinationDB].[dbo].Student
SELECT * FROM [SourceDB].[dbo].Student
GO

1 Comment

Hi, thanks for replying. I know this is a much simpler and "more logical" way but I need to create a script that would output another script containing INSERT stmts. Weird, I know :(.
0

If you have access to the both databases you can do it in one query like this:

INSERT INTO [Database A].[Table Student]
OUTPUT inserted.*
INTO [Database B].[Table Student]
SELECT *
FROM [newdata];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.