使用 T-SQL 插入 n 条记录 [英] Inserting n number of records with T-SQL

查看:31
本文介绍了使用 T-SQL 插入 n 条记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在表中添加可变数量的记录(天)

I want to add a variable number of records in a table (days)

我已经看到了一个巧妙的解决方案:

And I've seen a neat solution for this:

SET @nRecords=DATEDIFF(d,'2009-01-01',getdate())
SET ROWCOUNT @nRecords
INSERT int(identity,0,1) INTO #temp FROM sysobjects a,sysobjects b
SET ROWCOUNT 0

但遗憾的是,这在 UDF 中不起作用(因为 #temp 和 SET ROWCOUNT).知道如何实现这一目标吗?

But sadly that doesn't work in a UDF (because the #temp and the SET ROWCOUNT). Any idea how this could be achieved?

目前我正在使用 WHILE 和一个表变量来做这件事,但就性能而言,这不是一个好的解决方案.

At the moment I'm doing it with a WHILE and a table variable, but in terms of performance it's not a good solution.

推荐答案

这是我正在使用的方法,最适合我的目的和使用 SQL 2000.因为在我的情况下是在 UDF 中,我不能使用## 或 # 临时表,所以我使用表变量.我在做:

this is the approach I'm using and works best for my purposes and using SQL 2000. Because in my case is inside an UDF, I can't use ## or # temporary tables so I use a table variable. I'm doing:

DECLARE @tblRows TABLE (pos int identity(0,1), num int) 
DECLARE @numRows int,@i int


SET @numRows = DATEDIFF(dd,@start,@end) + 1
SET @i=1

WHILE @i<@numRows
begin
    INSERT @tblRows SELECT TOP 1 1 FROM sysobjects a

    SET @i=@i+1
end

这篇关于使用 T-SQL 插入 n 条记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆