开发者

Formulation of insert into keyword in SQL Server

开发者 https://www.devze.com 2023-03-31 04:33 出处:网络
I want to insert some values to the table, there is an order such as 1,2,3....n Insert Into table_name VALUES ( \'1\', \'A\' )

I want to insert some values to the table, there is an order such as 1,2,3....n

Insert Into table_name VALUES ( '1', 'A' )
Insert Into table_name VALUES ( '2', 'AA' )
Insert Into table_name VALUES ( '3', 'AAC' )
Insert Into table_name VALUES ( '.', '....' )
Insert Into table_name VALUES ( '.', '....' )
Inse开发者_StackOverflow社区rt Into table_name VALUES ( 'n', '....' )

How can I formulate this INSERT statement?


If you want to insert a series of rows - sure, you can use a loop - but how do you know what other values (other than the index) to get??

DECLARE @index INT
SET @index = 0

WHILE @index < 10
BEGIN
    INSERT INTO dbo.table_name(Index)
    VALUES( CAST(@index AS VARCHAR(50)) )  -- or whatever type you need....

    SET @index = @index + 1
END


The usual way to do this is to select the values to insert from somewhere else:

INSERT INTO company1.new_customers (id, name, address) 
SELECT 
  NULL   -- this will trigger the DB to auto-generate the new id's
  ,name
  ,address
FROM company2.old_customers

If you have to use a loop in SQL you're doing it wrong.
SQL works with sets.

0

精彩评论

暂无评论...
验证码 换一张
取 消