只是为了好玩,我想使用SQL创建可视骰子滚轮(我知道这不是该语言的设计目的。)
我想出了下面的代码,该代码将根据您的喜好掷骰子(@Dice
),并显示每个骰子的视觉表示,就像普通的六面骰子一样。
CREATE TABLE #Row1 ([1] CHAR(1), [2] CHAR(1), [3] CHAR(1))
CREATE TABLE #Row2 ([1] CHAR(1), [2] CHAR(1), [3] CHAR(1))
CREATE TABLE #Row3 ([1] CHAR(1), [2] CHAR(1), [3] CHAR(1))
DECLARE @Number INT
DECLARE @Count INT = 1
DECLARE @Dice INT = 2
WHILE @Count <= @Dice
BEGIN
SET @Number = ROUND(RAND(CONVERT(VARBINARY,NEWID()))*6,0,1)+1
INSERT INTO #Row1 ([1], [2], [3]) VALUES (
CASE WHEN @Number < 4 THEN ''
ELSE '•'
END
,''
,CASE WHEN @Number = 1 THEN ''
ELSE '•'
END
)
INSERT INTO #Row2 ([1], [2], [3]) VALUES (
CASE WHEN @Number <> 6 THEN ''
ELSE '•'
END
,CASE WHEN @Number % 2 = 0 THEN ''
ELSE '•'
END
,CASE WHEN @Number <> 6 THEN ''
ELSE '•'
END
)
INSERT INTO #Row3 ([1], [2], [3]) VALUES (
CASE WHEN @Number = 1 THEN ''
ELSE '•'
END
,''
,CASE WHEN @Number < 4 THEN ''
ELSE '•'
END
)
SELECT * FROM #Row1
UNION ALL
SELECT * FROM #Row2
UNION ALL
SELECT * FROM #Row3
TRUNCATE TABLE #Row1
TRUNCATE TABLE #Row2
TRUNCATE TABLE #Row3
SET @Count += 1
END
DROP TABLE #Row1
DROP TABLE #Row2
DROP TABLE #Row3
我的问题是,如何才能提高效率?没有这么多的UNION
,有没有办法做到这一点?
我也很感兴趣看到人们对扩展此主题/使其变得更有趣的任何想法!
答案 0 :(得分:4)
使用表变量而不是临时表。并在同一个表变量中包含所有三行:
DECLARE @Rows TABLE ([Row] INT, [1] NCHAR(1), [2] NCHAR(1), [3] NCHAR(1));
DECLARE @Number INT;
DECLARE @Count INT = 1;
DECLARE @Dice INT = 2;
WHILE @Count <= @Dice
BEGIN
SET @Number = ROUND(RAND(CONVERT(VARBINARY,NEWID()))*6,0,1)+1;
INSERT INTO @Rows ([Row], [1], [2], [3]) VALUES
(
1
,CASE WHEN @Number < 4 THEN N'' ELSE N'•' END
,N''
,CASE WHEN @Number = 1 THEN N'' ELSE N'•' END
),
(
2
,CASE WHEN @Number <> 6 THEN N'' ELSE N'•' END
,CASE WHEN @Number % 2 = 0 THEN N'' ELSE N'•' END
,CASE WHEN @Number <> 6 THEN N'' ELSE N'•' END
),
(
3
,CASE WHEN @Number = 1 THEN N'' ELSE N'•' END
,N''
,CASE WHEN @Number < 4 THEN N'' ELSE N'•' END
);
SELECT [1], [2], [3] FROM @Rows ORDER BY [Row];
DELETE FROM @Rows;
SET @Count += 1;
END;
编辑:
我更新了解决方案,以便将三个记录插入单个INSERT语句中,而不是为每个记录插入三个单独的INSERT语句。