Dav*_*leu 13 sql t-sql sql-server sql-server-2000
我想在表中添加可变数量的记录(天)
我已经看到了一个简洁的解决方案:
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
Run Code Online (Sandbox Code Playgroud)
但遗憾的是,这在UDF中不起作用(因为#temp和SET ROWCOUNT).知道如何实现这一目标吗?
目前我正在使用WHILE和表变量,但就性能而言,这不是一个好的解决方案.
Sco*_*vey 18
如果您使用的是SQL 2005或更高版本,则可以使用递归CTE获取日期或数字列表...
with MyCte AS
(select MyCounter = 0
UNION ALL
SELECT MyCounter + 1
FROM MyCte
where MyCounter < DATEDIFF(d,'2009-01-01',getdate()))
select MyCounter, DATEADD(d, MyCounter, '2009-01-01')
from MyCte
option (maxrecursion 0)
/* output...
MyCounter MyDate
----------- -----------------------
0 2009-01-01 00:00:00.000
1 2009-01-02 00:00:00.000
2 2009-01-03 00:00:00.000
3 2009-01-04 00:00:00.000
4 2009-01-05 00:00:00.000
5 2009-01-06 00:00:00.000
....
170 2009-06-20 00:00:00.000
171 2009-06-21 00:00:00.000
172 2009-06-22 00:00:00.000
173 2009-06-23 00:00:00.000
174 2009-06-24 00:00:00.000
(175 row(s) affected)
*/
Run Code Online (Sandbox Code Playgroud)
And*_*mar 11
您可以使用WHILE语句:
declare @i int
declare @rows_to_insert int
set @i = 0
set @rows_to_insert = 1000
while @i < @rows_to_insert
begin
INSERT INTO #temp VALUES (@i)
set @i = @i + 1
end
Run Code Online (Sandbox Code Playgroud)
这是我正在使用的方法,并且最适合我的目的并使用 SQL 2000。因为在我的例子中是在 UDF 内,所以我不能使用 ## 或 # 临时表,因此我使用表变量。我正在做:
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
Run Code Online (Sandbox Code Playgroud)