SQL Server Forums
Profile | Register | Active Topics | Members | Search | Forum FAQ
 
Register Now and get your question answered!
Username:
Password:
Save Password
Forgot your Password?

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 Insert multiple rows by count
 New Topic  Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

mutlyp
Starting Member

17 Posts

Posted - 10/13/2012 :  14:43:32  Show Profile  Reply with Quote
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
Flowing Fount of Yak Knowledge

5155 Posts

Posted - 10/14/2012 :  10:28:25  Show Profile  Reply with Quote
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
  Previous Topic Topic Next Topic  
 New Topic  Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.03 seconds. Powered By: Snitz Forums 2000