Nimchip
Nimchip

Reputation: 1735

how do I automatically execute a query that returns insert statements?

I wrote the following query in order to move some data to a joinTable:

SELECT 'insert into dbo.person_parks (person_id, parks_id) values
('+ cast([id] as nvarchar) +',' + [parks_id] + ');'
FROM [dbo].[person] where parks_id is not null

Now this works fine as it displays the correct insert queries which I then take and execute on a separate query window, but how do I make it so they are executed/inserted automatically instead of being only displayed as a dataset?

Sorry this may be super obvious and easy but I'm not that experienced in SQL-Server, I appreciate the help.

Upvotes: 0

Views: 35

Answers (2)

Kristian Oye
Kristian Oye

Reputation: 1202

Would be kinda curious to see why you would do this in the first place and how the code gets called. You could do insert and use an OUTPUT clause to show what was done instead. Beware of sql injection when doing dynamic sql (doesn't look like it would be an issue here).

Upvotes: 0

Roland Jansen
Roland Jansen

Reputation: 2783

INSERT INTO dbo.person_parks (person_id, parks_id)
SELECT CAST([id] as nvarchar), [parks_id]
FROM [dbo].[person] 
WHERE parks_id IS NOT NULL

Upvotes: 1

Related Questions