Click here to Skip to main content
15,888,401 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
CREATE PROCEDURE writeNo
AS
DECLARE @slno INT
SET @slno = 1
WHILE @slno <= 9999
BEGIN
SET NOCOUNT ON 
 INSERT INTO [dbslno].[dbo].tblslno(slno)
     values(@slno)  
SET @slno = @slno + 1
END
SELECT * FROM tblslno
GO

tried this and its not working.
Posted

You don't need to have a loop for getting a serial number 1..9999. This can be done without any loop/iteration at all. See below for a sampel code.

SQL
CREATE PROCEDURE writeNo
AS
BEGIN
	SET NOCOUNT ON 
	INSERT INTO [dbslno].[dbo].tblslno(slno)
	SELECT n
	FROM
	(
		SELECT TOP (9999) n = CONVERT(INT, ROW_NUMBER() OVER (ORDER BY s1.[object_id]))
		FROM sys.all_objects AS s1 CROSS JOIN sys.all_objects AS s2
	) a

	SELECT *
	FROM	[dbslno].[dbo].tblslno
END
GO

exec writeNo
GO
 
Share this answer
 
v4
Comments
kiran gowda8 23-Jul-15 4:05am    
how to insert that in to table??
_Asif_ 23-Jul-15 4:33am    
Solution modified! Please check
Herman<T>.Instance 23-Jul-15 4:56am    
Nice! +5
kiran gowda8 23-Jul-15 4:58am    
thank you _Asif_.!!
Animesh Datta 23-Jul-15 5:14am    
My 5!
I'd prefer something a little more self reliant:

SQL
CREATE PROCEDURE writeNo
AS
BEGIN

	WITH mycte AS (
		SELECT 1 AS number
		UNION ALL SELECT number + 1 FROM mycte
		WHERE number < 9999
	) 
	INSERT INTO [dbslno].[dbo].tblslno(slno)
	SELECT number FROM mycte
	OPTION (MAXRECURSION 9999)

END


Yay for recursive Common Table Expressions (cte) ^_^
 
Share this answer
 
Comments
_Asif_ 23-Jul-15 5:05am    
+5 :)
Animesh Datta 23-Jul-15 5:14am    
5!
Andy Lanng 23-Jul-15 5:24am    
ooh so much attention. I blush ^_^

I might just point out that in this case Asif's solution is s little more efficient :)
kiran gowda8 23-Jul-15 6:31am    
thank you Andy Lanng :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900