Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 Insert multiple rows by count

Author  Topic 

mutlyp
Starting Member

20 Posts

Posted - 2012-10-13 : 14:43:32
I need to insert multiple rows of data into a table with the only thing being different is the CodeNumber. The CodeNumber needs to be incremented by 1 for each row to be inserted.
Example:

Insert into table (CodeNumber, Name) Values (@num, @name)
So if I need to insert 5 rows it should look like this in the table:
CodeNumber Name
0205 Bashire
0206 Bashire
0207 Bashire
0208 Bashire
0209 Bashire
What I am doing now is using a loop in my client code to insert the multiple rows. I was hoping there was a sql statement that I could use in a stored procedure to do this so I don't need to make so many multiple calls to the server.
Obviously I don't want to use the cursor loop because I hear that is wrong so hopefully there is a better way to do this.
Thank you

sunitabeck
Master Smack Fu Yak Hacker

5155 Posts

Posted - 2012-10-14 : 10:28:25
Something like this:
INSERT INTO tbl (codenumber, name)
SELECT
number+@num,
@name
FROM
MASTER..spt_values v
WHERE v.[type] = 'p'
WHERE
number < 5;
I qualifying by saying "something like" because, it won't give you the prefixed zero's that you are looking for if the data type of codenumber is numeric. If the data type is not numeric, what I posted above will not work.
Go to Top of Page
   

- Advertisement -