Randomly Select a Row with SQL in Access

后端 未结 4 1007
梦毁少年i
梦毁少年i 2020-12-22 00:27

I have a small access database with some tables. I am trying the code in the sql design within access. I just want to randomly select a record within a table.

I cre

相关标签:
4条回答
  • 2020-12-22 01:04

    Please try this, it is helpful to you

    It is possible by using a stored procedure and function, which I created it's have a extra column which you could be create in your table FLAG name and column all field value should be 0 Then it works

    create Procedure proc_randomprimarykeynumber
    as
        declare @Primarykeyid int  
    
        select top 1  
            @Primarykeyid = u.ID 
        from 
            StateAbbreviation u  
        left join  
            StateAbbreviation v on u.ID = v.ID + 1 
        where 
            v.flag = 1 
    
        if(@Primarykeyid is null )
        begin
            UPDATE StateAbbreviation 
            SET flag = 0  
    
            UPDATE StateAbbreviation 
            SET flag = 1 
            WHERE ID IN (SELECT TOP 1 ID 
                         FROM dbo.StateAbbreviation)
        END
        ELSE
        BEGIN
            UPDATE StateAbbreviation 
            SET flag = 0 
    
            UPDATE StateAbbreviation 
            SET flag = 1 
            WHERE ID IN (@Primarykeyid)
        END 
    
        SET @Primarykeyid = 1 
    
        SELECT TOP 1 
            ID, Abbreviation 
        FROM
            StateAbbreviation 
        WHERE
            flag = 1
    

    It is made in stored procedure run this and get serial wise primary key

    exec proc_randomprimarykeynumber
    

    Thanks and regard

    0 讨论(0)
  • 2020-12-22 01:08

    You need both a variable and a time seed to not get the same sequence(s) each time you open Access and run the query - and to use Access SQL in Access:

    SELECT TOP 1 Abbreviation
    FROM STATEABBREVIATION
    ORDER BY Rnd(-Timer()*[ID]);
    

    where ID is the primary key of the table.

    0 讨论(0)
  • 2020-12-22 01:14

    Ypercude provided a link that led me to the right answer below:

    SELECT TOP 1 ABBREVIATION
    FROM STATEABBREVIATION 
    ORDER BY RND(ID);
    

    Note that for RND(), I believe that it has to be an integer value/variable.

    0 讨论(0)
  • 2020-12-22 01:20

    Try this:

    SELECT TOP 1 *
    FROM tbl_name
    ORDER BY NEWID()
    

    Of course this may have performance considerations for large tables.

    0 讨论(0)
提交回复
热议问题