从数据库中获取随机记录以进行测验游戏

时间:2013-04-04 06:28:57

标签: c# asp.net sql-server web-services windows-phone-7

我想要您的帮助来创建查询。我是软件事业的新手,我正在尝试为Windows Mobile应用程序开发KBC Type Quiz游戏。对于我想要尝试从数据库中获取随机记录,如果在该记录之后一次出现一条记录将不再出现。我使用此查询"SELECT TOP 1 * FROM Quiz ORDER BY NEWID()"但记录重复。

我的表格结构如下。

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服务

1 个答案:

答案 0 :(得分:1)

只需将Quiz中的列添加为bool并将其设置为默认值

然后使你的存储过程像它一样帮助你使用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