Select 4 records, Randomly from Database

Discussion in 'ASP General' started by tamaker, Dec 12, 2007.

  1. tamaker

    tamaker Guest

    Is this do-able with ASP / VBscript?

    -- I have a database with user records (name, photo, etc. etc.)

    I want to use asp to generate (on the homepage) a series of 4 randomly
    selected 'user records' from the database -- say just the headshot
    photo or name from the database.

    In addition to the recordset being randomly generated (i.e. our of
    about 50 records, only records 4, 18, 23 and 26 are displayed) I need
    to MAKE SURE they are not duplicated (i.e. out of the 50 records,
    records 4, 18, 23 and 23 -- where the last two are duplicates).

    Is there a way I can pull this off and how do I go about it exactly?

    tamaker, Dec 12, 2007
    1. Advertisements

  2. tamaker

    Bruce Guest

    1) get the number of records (users in the database)
    2) generate 4 random numbers, make sure that they are not the same, and the
    they are not higher than the total number of users (let's say that you got
    12,25,28 and 30)
    3) choose the highest number that you selecte (among the 4 random numbers)
    (that will be 30)
    4) select top 30 * from users (assuming that 30 is the highest number). This
    will get 30 users from the database
    5) loop thru the records, when you're at the random numbers, display them
    (meaning that you display only 12,25,28 and 30).

    This isn't the most optimized way, but try it and make it work. You can
    always tweak it later.

    Hope this helps
    Bruce, Dec 12, 2007
    1. Advertisements

  3. tamaker

    Bob Lehmann Guest

  4. tamaker

    Dooza Guest

    I have a stored procedure that does this, here is the SQL is uses:

    SELECT TOP 5 item, desc, picture
    FROM dbo.products

    I haven't seen it create any duplicates yet.

    Dooza, Dec 13, 2007
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.