我需要将带有随机@N
值的float
行插入到一个表中,并将每个新插入行的ID用于另一个INSERT
。我需要在存储过程中做这一切。例如:
CREATE PROCEDURE Proc
@N int
AS
-- START LOOP, REPEAT @N TIMES
INSERT INTO [T1]
([Value])
VALES
(<random_float>)
INSERT INTO [T2]
([ValueID])
VALUES
(@@IDENTITY)
-- END LOOP
END
GO
提前致谢。
答案 0 :(得分:4)
没有循环,一个插入
;WITH cte AS
( --there are easier ways to build a numbers table
SELECT
ROW_NUMBER() OVER (ORDER BY (select 0)) AS rn
FROM
sys.columns c1 CROSS JOIN sys.columns c2 CROSS JOIN sys.columns c3
)
INSERT INTO [T1] ([Value])
OUTPUT INSERTED.ID INTO T2 -- direct insert to T2
SELECT RAND(CHECKSUM(NEWID()))
FROM cte
WHERE rn <= @N;
答案 1 :(得分:1)
目前还不完全清楚你要做什么。你的意思是这样的:
create table dbo.RandomTable
(
rowid int not null PRIMARY KEY,
pure_random float null,
)
declare @row int
set @row = 1
while (@row <= @N)
begin
insert into dbo.RandomTable (rowid, pure_random)
values (@row, rand())
set @row = @row + 1
end
[我不主张使用循环;这不是最有效的方式。这就是海报要求的形式......]
答案 2 :(得分:1)
CREATE TABLE [T1]
(
[ValueID] INT IDENTITY(1,1),
[Value] FLOAT
)
GO
CREATE TABLE [T2]
(
[ValueID] INT
)
GO
CREATE PROCEDURE [Proc]
@N int
AS
BEGIN
DECLARE @i INT = 0;
WHILE (@i < @N)
BEGIN
INSERT INTO [T1]
([Value])
SELECT RAND()
INSERT INTO [T2]
([ValueID])
VALUES
(SCOPE_IDENTITY())
SET @i += 1
END
END
GO
TRUNCATE TABLE T1
TRUNCATE TABLE T2
EXEC [Proc] @N = 10