我有一个表ABSENCE,它有40个员工ID,需要从表变量中添加两列,作为参考表。对于每个emp id,我需要从表变量中随机分配值。这是我在没有随机化的情况下尝试的代码:
USE TSQL2012;
GO
DECLARE @MAX SMALLINT;
DECLARE @MIN SMALLINT;
DECLARE @RECODE SMALLINT;
DECLARE @RE CHAR(100);
DECLARE @rearray table (recode smallint,re char(100));
insert into @rearray values (100,'HIT BY BEER TRUCK')
,(200,'BAD HAIR DAY')
,(300,'ASPIRIN OVERDOSE')
,(400,'MAKEUP DISASTER')
,(500,'GOT LOCKED IN THE SALOON')
DECLARE @REFCURSOR AS CURSOR;
SET @REFCURSOR = CURSOR FOR
SELECT RECODE,RE FROM @REARRAY;
OPEN @REFCURSOR;
SET @MAX = (SELECT DISTINCT @@ROWCOUNT FROM ABSENCE);
SET @MIN = 0;
ALTER TABLE ABSENCE ADD CODE SMALLINT, REASONING CHAR(100);
WHILE (@MIN <= @MAX)
BEGIN
FETCH NEXT FROM @REFCURSOR INTO @RECODE,@RE;
INSERT INTO ABSENCE (CODE, REASONING) VALUES (@RECODE,@RE);
SET @MIN+=1;
END
CLOSE @REFCURSOR
DEALLOCATE @REFCURSOR
SELECT EMPID,CODE,REASONING FROM ABSENCE
虽然我只插入两列,但是它试图插入empid(已经填充)并且因为它不能为NULL,插入失败。
另外,如何随机化REARRAY表变量中的值以将它们插入到ABSENCE表中?
答案 0 :(得分:0)
由于这是一个小型数据集,因此一种方法可能是CROSS APPLY
采用SELECT TOP(1) ... FROM @rearray ORDER BY NEWID()
方法。这将基本上将ABSENCE
表与您的引用表一起加入UPDATE
语句中,每次在连接中选择一个随机行。完整的,它看起来像:
UPDATE ABSENCE
SET col1 = x1.recode, col2 = x2.recode
FROM ABSENCE a
CROSS APPLY (SELECT TOP(1) * FROM @rearray ORDER BY NEWID()) x1(recode, re)
CROSS APPLY (SELECT TOP(1) * FROM @rearray ORDER BY NEWID()) x2(recode, re)