Monday, March 26, 2012

Multiple insert command

Is it possible to insert a row, where you want to insert the same data in the row, but just change a number?

In vb i would use this for example (not actually the code, just an example)

For x=1 to 10

sql = "Insert into (Number, .... .. ) values (" & x & ", ......)

execute command

Next

Is it possible to make one command where i could something like this?

There are many ways of doing it depending on your requirements. Below is a simple example that assumes that you have variables with the data and you want to insert say 10 rows:

Code Snippet

insert into your_table (id, ....)

select top(10) row_number() over(order by object_id) as seq, @.col1, @.col2, @.col3

from sys.objects

order by object_id

-- You can also generate more rows on the fly using cross join of several tables like

insert into your_table (id, ....)

select top(1000) row_number() over(order by o1.object_id) as seq, @.col1, @.col2, @.col3

from sys.objects as o1 cross sys.objects as o2

order by o1.object_id

No comments:

Post a Comment