Welcome to Sign in | Help
in Search

One random record

Last post 10-22-2007, 8:22 AM by alinescoo. 5 replies.
Sort Posts: Previous Next
  •  10-19-2007, 11:07 AM 2987

    One random record

    Am o tabela in care am campurile: locatie, depozit. Inainte, nu aveam campul depozit, iar pt a alege o locatie random din tabela faceam:

    Select top1 locatie

    from tablea

    Order by newid().

     

    Ei, acum situatia e alta, si vreau sa fac random locatie doar pt un anumit depozit care sa fie parametru si sa il trimit eu. Pt asta m-am gandit la o functie tabela... problema e ca nu pot folosi newid() in functie, Ce alte alternative imi recomandati ?

  •  10-19-2007, 11:50 AM 2988 in reply to 2987

    Re: One random record

    Poate reusiti cu functia random

    exemplu de folosire dat de Cristi Lefter aici


    Gheorghe Ciubuc,SQL Server Influencer, MCP(SQL 2000), MCTS (SQL Server 2005) , OCA(Oracle 9i), Sybase(Brainbench)
  •  10-19-2007, 11:55 AM 2989 in reply to 2987

    Re: One random record

    alinescoo:

    Am o tabela in care am campurile: locatie, depozit. Inainte, nu aveam campul depozit, iar pt a alege o locatie random din tabela faceam:

    Select top1 locatie

    from tablea

    Order by newid().

     

    Ei, acum situatia e alta, si vreau sa fac random locatie doar pt un anumit depozit care sa fie parametru si sa il trimit eu. Pt asta m-am gandit la o functie tabela... problema e ca nu pot folosi newid() in functie, Ce alte alternative imi recomandati ?

     

    Select Top 1 Locatie From Tablela Where Depozit = @Depozit Order By NewId()

  •  10-19-2007, 12:43 PM 2990 in reply to 2989

    Re: One random record

    As fi vrut sa fie chestia asta intr-o functie... si cum cu newID() nu merge in functie. Asa selectul independent merge, insa deoarece o folosesc in mai multe locuri mi-ar fi mai usor sa fie o functie.

    Cat despre RAND()... as prefera o alta varianta. 

    Va multumesc pentru raspunsuri.

  •  10-19-2007, 4:05 PM 2995 in reply to 2990

    Re: One random record

    Poţi să pui apelul funcţiei NEWID() într-un view, iar în funcţie să referi view-ul respectiv, de exemplu:

    USE Northwind
    GO
    CREATE VIEW RandomOrders
    AS
    SELECT OrderID, EmployeeID, NEWID() as RandomID FROM Orders
    GO
    CREATE FUNCTION GetRandomOrder(@EmployeeID int)
    RETURNS INT AS BEGIN
        RETURN (SELECT TOP 1 OrderID FROM RandomOrders WHERE EmployeeID=@EmployeeID ORDER BY RandomID)
    END
    GO
    SELECT dbo.GetRandomOrder(1)
    SELECT dbo.GetRandomOrder(1)
    SELECT dbo.GetRandomOrder(1)

    Răzvan

  •  10-22-2007, 8:22 AM 3030 in reply to 2995

    Re: One random record

    Verry verry nice. Mersi, asa o sa fac.
View as RSS news feed in XML
Powered by Community Server (Commercial Edition), by Telligent Systems