使用来自不同表的随机值填充列

时间:2015-03-27 07:19:11

标签: sql sql-server tsql

我有2张桌子。表Table_View有5列200行 Table_Random有3列10行 我需要使用来自的值来填充列Table_View.A_random Table_Random.FixValues。如果查询到达Table_Random i.e row 10中的行尾,则应该重新开始 顶行i.e row 1中的值。直到它填满200行。 鉴于所有表都有primary keys

任何想法? 提前致谢

2 个答案:

答案 0 :(得分:1)

这适用于目标和源表中的任何行数。 我们的想法是计算随机表中的行数,然后将数字rn % @c分配给目标表中的每一行。然后根据加入更新:

DECLARE @count INT = 21
DECLARE @i INT = 1
DECLARE @c INT = 0

DECLARE @t TABLE ( ID INT, Random INT )
DECLARE @r TABLE ( ID INT, Random INT )

INSERT  INTO @r
VALUES  ( 1, 10 ),
        ( 3, 20 ),
        ( 4, 30 ),
        ( 6, 40 ),
        ( 8, 50 ),
        ( 11, 60 ),
        ( 14, 70 ),
        ( 17, 80 ),
        ( 19, 90 ),
        ( 21, 100 )

WHILE @i <= @count
    BEGIN
        INSERT  INTO @t
        VALUES  ( @i, NULL )

        SET @i = @i + 1
    END;

SELECT  @c = COUNT(*)
FROM    @r;


WITH    ctet1
          AS ( SELECT   * , ROW_NUMBER() OVER ( ORDER BY ID ) AS rn
               FROM     @t
             ),
        ctet2
          AS ( SELECT   * ,
                        CASE WHEN rn % @c = 0 THEN @c
                             ELSE rn % @c
                        END AS rnn
               FROM     ctet1
             ),
        cter
          AS ( SELECT   * , ROW_NUMBER() OVER ( ORDER BY ID ) AS rn
               FROM     @r
             )

    UPDATE  ct
    SET     Random = cr.Random
    FROM    ctet2 ct
            JOIN cter cr ON cr.rn = ct.rnn

SELECT  * FROM    @t    

输出:

ID  Random
1   10
2   20
3   30
4   40
5   50
6   60
7   70
8   80
9   90
10  100
11  10
12  20
13  30
14  40
15  50
16  60
17  70
18  80
19  90
20  100
21  10

如果您不想要循环更新,则不需要视图,功能和不必要的东西。只需更新:

UPDATE @t SET Random = (SELECT TOP 1 Random FROM @r ORDER BY NEWID()) 

答案 1 :(得分:1)

  

是的,你可以解决这个问题。

首先,您需要为每次调用创建和查看哪个&lt; ll将从随机表(Table_Random)返回单个值。

Create View vMyRand as 
Select top 1 val from myRand order by NewID();

然后创建一个函数以从创建的视图返回值。

CREATE FUNCTION GetMyRand ()
RETURNS varchar(5)
--WITH EXECUTE AS CALLER
AS
BEGIN
Declare @RetValue varchar(5)
--@configVar =
Select @RetValue = val from vmyRand
RETURN(@retValue)
END;

Fiddle Demo Here

完整代码:

create table tab_1
(
  id bigint identity(1,1),
  name varchar(50),
  email varchar(50)
  )

  insert into tab_1(name,email) values
  ('a','a@mail.com'),  ('b','c@mail.com'),
    ('a1','a1@mail.com'),  ('a2','a2@mail.com'),
      ('a3','a3@mail.com'),  ('a4','a4@mail.com'),
      ('b1','b1@mail.com'),('b2','b2@mail.com')

   create table myRand(val varchar(50))

   insert into myRand values('Q1654'),('F2597'),
   ('Y9405'),('B6735'),('D8732'),('C4893'),('I9732'),
   ('L1060'),('H6720');

Create View vMyRand as 
Select top 1 val from myRand order by NewID();

CREATE FUNCTION GetMyRand ()
RETURNS varchar(5)
--WITH EXECUTE AS CALLER
AS
BEGIN
Declare @RetValue varchar(5)
--@configVar =
Select @RetValue = val from vmyRand
RETURN(@retValue)
END;

更新代码:

update tab_1 set name=(select dbo.getMyRand())

希望这会帮助你。 谢谢。 :)