2011-09-25 98 views
0

我需要將@N行隨機float值插入到一個表中,並將每個新插入行的ID用於另一個INSERT。這一切我需要在存儲過程中完成。例如:將N個隨機值插入表

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

隨機漂浮界限之間? '@ N'還有一個最大值,超過這個值你不會去? –

+0

界限無關緊要。例如'@ min'和'@ max'。 '@ N'無限制# –

+0

從實際角度來看,'@ N'會有一個限制。你打算用這個來插入一萬億行嗎? –

回答

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

@@ gbn:是OPTION(MAXRECURSION 0);需要? –

+1

雖然它不會插入到「T2」? –

+0

@Mitch小麥:好點,非遞歸CTE不需要。謝謝 – gbn

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 

[我不主張使用循環;這不是最有效的方法。這只是那海報被要求...]

0
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 

WHILE (Transact-SQL)SCOPE_IDENTITY (Transact-SQL)