如何一次插入多条记录的SQL语句?
1个回答
2022-12-11 · 百度认证:北京惠企网络技术有限公司官方账号
关注
展开全部
在使用SQL数据库的时候,我们也许会需要一次像数据库中添加多条记录,那么我们可以使用SQL语句来实现,该语句具体如下:\x0d\x0a--添加一条记录 \x0d\x0aINSERT INTO tableName(col1,col2,col3) VALUES (1,2,3) \x0d\x0a \x0d\x0a--添加多条记录 \x0d\x0aINSERT INTO tableName(col1,col2,col3) \x0d\x0aSELECT 3,4,5 \x0d\x0aUNION ALL \x0d\x0aSELECT 6,7,8 \x0d\x0a \x0d\x0a--从另外的一张表中读取多条数据添加到新表中 \x0d\x0aINSERT INTO tableName(col1,col2,col3) \x0d\x0aSELECT a,b,c FROM tableA \x0d\x0a \x0d\x0a--从其他的多张表中读取数据添加到新表中 \x0d\x0aINSERT INTO tableName(col1,col2,col3) \x0d\x0aSELECT a,b,c FROM tableA WHERE a=1 \x0d\x0aUNION ALL \x0d\x0aSELECT a,b,c FROM tableB WHERE a=2 \x0d\x0a上边代码中的into都可以省略!\x0d\x0a上边代码中的union all如果换成union,则相同记录只插入一次,不会重复插入。\x0d\x0a另外一种方法是SQL Server2008特有的,所以,如果你不是SQL Server2008,就不能使用这种方法了。 \x0d\x0aINSERT INTO MyTable(ID,NAME)VALUES(7,'003'),(8,'004'),(9,'005')\x0d\x0acreate table [TEST]\x0d\x0a(\x0d\x0a [NUM_ID] int primary key\x0d\x0a)\x0d\x0ago\x0d\x0adeclare @temp int\x0d\x0aset @temp=1;\x0d\x0awhile @temp<=1000000 \x0d\x0abegin\x0d\x0ainsert into [TEST]([NUM_ID]) values(@temp)\x0d\x0aset @temp=@temp+1;\x0d\x0aend\x0d\x0ago\x0d\x0a----------------------------------------------------------\x0d\x0a--试试下面的方法\x0d\x0a--2005\x0d\x0aDECLARE @n AS BIGINT;\x0d\x0aSET @n = 1000000;\x0d\x0aWITH Base AS\x0d\x0a(\x0d\x0a SELECT 1 AS n\x0d\x0a UNION ALL\x0d\x0a SELECT n + 1 FROM Base WHERE n < CEILING(SQRT(@n))\x0d\x0a),\x0d\x0aExpand AS\x0d\x0a(\x0d\x0a SELECT 1 AS c\x0d\x0a FROM Base AS B1, Base AS B2\x0d\x0a),\x0d\x0aNums AS\x0d\x0a(\x0d\x0a SELECT ROW_NUMBER() OVER(ORDER BY c) AS n\x0d\x0a FROM Expand\x0d\x0a)\x0d\x0aSELECT n FROM Nums WHERE n <= @n\x0d\x0aOPTION(MAXRECURSION 0);\x0d\x0a--2\x0d\x0aCREATE FUNCTION dbo.fn_nums(@n AS BIGINT) RETURNS TABLE\x0d\x0aAS\x0d\x0aRETURN\x0d\x0a WITH\x0d\x0a L0 AS(SELECT 1 AS c UNION ALL SELECT 1),\x0d\x0a L1 AS(SELECT 1 AS c FROM L0 AS A, L0 AS B),\x0d\x0a L2 AS(SELECT 1 AS c FROM L1 AS A, L1 AS B),\x0d\x0a L3 AS(SELECT 1 AS c FROM L2 AS A, L2 AS B),\x0d\x0a L4 AS(SELECT 1 AS c FROM L3 AS A, L3 AS B),\x0d\x0a L5 AS(SELECT 1 AS c FROM L4 AS A, L4 AS B),\x0d\x0a Nums AS(SELECT ROW_NUMBER() OVER(ORDER BY c) AS n FROM L5)\x0d\x0a SELECT n FROM Nums WHERE n <= @n;\x0d\x0aGO\x0d\x0a--2000 这个会比前两个慢,但是前两个2000不能用\x0d\x0aCREATE TABLE dbo.Nums(n INT NOT NULL PRIMARY KEY);\x0d\x0aDECLARE @max AS INT, @rc AS INT;\x0d\x0aSET @max = 1000000;\x0d\x0aSET @rc = 1;\x0d\x0aINSERT INTO Nums VALUES(1);\x0d\x0aWHILE @rc * 2 <= @max\x0d\x0aBEGIN\x0d\x0a INSERT INTO dbo.Nums SELECT n + @rc FROM dbo.Nums;\x0d\x0a SET @rc = @rc * 2;\x0d\x0aEND\x0d\x0aINSERT INTO dbo.Nums\x0d\x0a SELECT n + @rc FROM dbo.Nums WHERE n + @rc <= @max; \x0d\x0a--------------------------------------------------------------------------------------------------------
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询
广告 您可能关注的内容 |