0

I'm trying to insert the same record into multiple databases on the same server, I've already done this with cursors but I need to do it without them, how can I do something like this?

Logic example (this isn't a correct example, just an example to explain myself):

INSERT INTO (SELECT name FROM sys.databases)
    SELECT '1', 'asd', 'dsa'

What I don't understand is how can I change the database without the cursor.

Thanks in advance

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Guedesss
  • 1
  • 2
  • 1
    Whats wrong with a cursor? That's an acceptable tool for the job when doing something like this. (sp_MSForEachDB uses cursors itself) – Alex K. Sep 05 '17 at 11:19
  • You can ask someone else to loop over databases for you. As @dlatikay said `sp_MSForEachDB` can do it. Alternatively use https://www.mssqltips.com/sqlservertip/2201/making-a-more-reliable-and-flexible-spmsforeachdb/ – Serg Sep 05 '17 at 11:26
  • Firstly, you don't insert into multiple databases **EVER**. You insert into tables. So your current path does not make any sense for a number of reasons. Do you expect every table in every database to have the same columns? And you surely do not want to include the system databases in this quest. So instead of focusing on "how", let's focus on what you are trying to do first - and then figure out how to do it. – SMor Sep 05 '17 at 14:04
  • First of all, thanks to all of you for the help, it's resolved now. @SMor, I do know I insert into tables, the example I gave was just for easier understanding my point; and yes, it's not for all tables, I do have a Where condition in my code. – Guedesss Sep 05 '17 at 15:41

0 Answers0