从数据库中获取随机记录进行问答游戏

本文关键字:问答 游戏 记录 随机 数据库 获取 | 更新日期: 2023-09-27 18:07:31

我想帮助你创建一个查询。我在软件事业的新,我正在努力开发一个KBC类型的问答游戏为Windows移动应用程序。为此,我想尝试从数据库中获取随机记录,如果一个记录在同一时间出现,该记录将不会再次出现。我使用这个查询"SELECT TOP 1 * FROM Quiz ORDER BY NEWID()",但记录是重复的。

My Table结构如下:

ColumnName  DataType
Id          int
Que         varchar(150)
Ans1        varchar(100)
Ans2        varchar(100)
Ans3        varchar(100)
TrueAns     varchar(100)

我也尝试创建一个存储过程,如下所示

DECLARE @counter int, @randno int, @uBound int, @lBound int

        SELECT @uBound = Max(Id) FROM Quiz
        SELECT @lBound = Min(Id) FROM Quiz
        SELECT @randno = Round(((@uBound - @lBound) * Rand() + @lBound), 0)
        SET @Counter = 0
        WHILE @counter = 0
        BEGIN
            IF EXISTS(SELECT Id FROM Quiz WHERE Id = @randno)
            BEGIN
                SET NOCOUNT OFF
                SELECT * FROM Quiz WHERE Id = @randno
                SET @counter = 1
            END
            ELSE
            BEGIN
                SELECT @randno = Round(((@uBound - @lBound -1 ) * Rand() + @lBound), 0)
            END
        END

但是我不能获得成功。我的表包含如下字段:Que, Ans1, Ans2, Ans3, TrueAns。请帮我解决这个问题。我还想创建一个web服务,返回所有的记录

从数据库中获取随机记录进行问答游戏

只需在Quiz isread中添加一个列作为bool并将其设置为默认false

然后让你的存储过程像它将帮助你去webservice方法

DECLARE @counter int, @randno int, @uBound int, @lBound int

        SELECT @uBound = Max(Id) FROM Quiz
        SELECT @lBound = Min(Id) FROM Quiz
        SELECT @randno = Round(((@uBound - @lBound) * Rand() + @lBound), 0)
        SET @Counter = 0
        WHILE @counter = 0
        BEGIN

If(( select count(*) from Quiz where isread= true)=( select count(*) from Quiz ))
BEGIN
 update Quiz SET isread=false  
End
            IF EXISTS(SELECT Id FROM Quiz WHERE Id = @randno and isread=false )
            BEGIN
            update Quiz SET isread=true  WHERE Id = @randno                   
            SET NOCOUNT OFF
                SELECT * FROM Quiz WHERE Id = @randno
                SET @counter = 1
            END
            ELSE
            BEGIN
                SELECT @randno = Round(((@uBound - @lBound -1 ) * Rand() + @lBound), 0)
            END
        END