How can I add “X” rows to a table in SQL?

心不动则不痛 提交于 2019-12-25 18:42:09

问题


If I have a table, let's say Customers and I want to receive from the user a number (Form) and create X rows in the Customer table. Let's say the customer put the number 4 I want 4 new rows at the Customer Table. How can I do this?

insert into Customer Valus ('Helen' , 36 )

回答1:


You could use a stored procedure and then pass the number of customers you want added. Something like this...

create procedure AddNewCustomers 
@NumberOfCustToAdd int 
as 

declare @counter int 

set @counter = 0 

while @counter < @NumberOfCustToAdd
begin
    //put your insert statement here
    set @counter = @counter + 1
end

go

Then, call the procedure passing the number of customers that the user requested...

exec AddNewCustomers @NumberOfCustomersToCreate



回答2:


Is this what you want -

INSERT INTO Customers(Name)
VALUES(NULL)
GO 10

This will insert 10 rows which you can update later.




回答3:


Here you go, this will generate 4 identical rows from passed in variables. This will max out at 100 rows.

Un-comment and correct insert statement as you see fit.

DECLARE @I INT, @NAME NVARCHAR(10)
SET @NAME = 'HELEN'
SET @I=4

;WITH MYCTE
AS
(
SELECT @NAME AS NAME, X=1
UNION ALL 
SELECT NAME, X+1
FROM MYCTE
WHERE X<@I
)
-- INSERT INTO...
SELECT * 
FROM MYCTE OPTION(MAXRECURSION 100)


来源:https://stackoverflow.com/questions/22412307/how-can-i-add-x-rows-to-a-table-in-sql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!