如何将此代码更改为SQL Server 2000,以便均匀分配颜色?

时间:2016-01-21 13:15:50

标签: sql-server tsql sql-server-2000

如何将此代码更改为SQL Server 2000,以便均匀分配颜色

DECLARE @Employees TABLE
(
       Name VARCHAR(10)
)

INSERT INTO @Employees (Name) 
VALUES ('Sam'), ('John'), ('Jack'), ('April'), ('Sonny'), ('Jill'), ('Jane');

DECLARE @Colors TABLE
(
       Name VARCHAR(10)
)

INSERT INTO @Colors (Name) 
VALUES ('Red'), ('Green'), ('Blue');

DECLARE @ColorCount INT
SELECT @ColorCount = COUNT(*) FROM @Colors

;WITH Employees(SNumber, Name) AS
(
       SELECT ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) AS SNumber, Name
       FROM @Employees
    ), 
    Colors(CNumber, Name) AS
    (
       SELECT ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) AS CNumber, Name 
       FROM @Colors 
    )

SELECT E.Name, C.Name FROM Employees E
INNER JOIN Colors C ON 
       CASE 
       WHEN (E.SNumber % @ColorCount) = 0 
            THEN @ColorCount 
            ELSE E.SNumber % @ColorCount 
       END = C.CNUmber

结果:

Sam - Red
April - Red    
Jane - Red
John - Green
Sonny - Green
Jack - Blue
Jill - Blue

1 个答案:

答案 0 :(得分:0)

应转换SQL Server 2000中不可用的两件事:

  • ROW_NUMBER:这可以通过在IDENTITY的临时表中填充CTE来分配数字来完成
  • CTE:在临时表中填写CTE并在最终查询中使用它们。

您的脚本如下所示:

DECLARE @Employees TABLE
(
       Name VARCHAR(10)
)

INSERT INTO @Employees (Name) 
VALUES ('Sam'), ('John'), ('Jack'), ('April'), ('Sonny'), ('Jill'), ('Jane');

DECLARE @Colors TABLE
(
       Name VARCHAR(10)
)

INSERT INTO @Colors (Name) 
VALUES ('Red'), ('Green'), ('Blue');

DECLARE @ColorCount INT
SELECT @ColorCount = COUNT(*) FROM @Colors

CREATE TABLE #Employees(SNumber INT IDENTITY(1,1), Name VARCHAR(10));
INSERT INTO #Employees(Name) SELECT Name FROM @Employees;

CREATE TABLE #Colors(CNumber INT IDENTITY(1,1), Name VARCHAR(10));
INSERT INTO #Colors(Name) SELECT Name FROM @Colors;

SELECT E.Name, C.Name FROM #Employees E
INNER JOIN #Colors C ON 
       CASE 
       WHEN (E.SNumber % @ColorCount) = 0 
            THEN @ColorCount 
            ELSE E.SNumber % @ColorCount 
       END = C.CNUmber

DROP TABLE #Employees;
DROP TABLE #Colors;