Random Function

Jan 25, 2006

Hi all,

I have a table with a multiple fields. I want to create a query that it will show me one dataset according to a random numder the system choose...

For istanse if it choose the number 13 it will show all the records conserning that id

I used the following query, but of course it is wrong

select * from famous_queries
where id = rand(id)


Could someone help me with this please?

View 15 Replies


ADVERTISEMENT

Dynamic SQL And NewID Function - Pulling Random Records

Jun 11, 2007

I'm trying to use the NEWID function in dynamic SQL and get an errormessage Incorrect syntax near the keyword 'ORDER'. Looks like I can'tdo an insert with an Order by clause.Here's the code:SELECT @SQLString = N'INSERT INTO TMP_UR_Randoms(Admit_DOCID,Client_ID, SelectDate, SelectType,RecordChosen)'SELECT @SQLString = @SQLString + N'(SELECT TOP ' + @RequFilesST + 'Admit_DOCID, Client_ID, SelectDate, SelectType, RecordChosen FROMFD__UR_Randoms 'SELECT @SQLString = @SQLString + N'WHERE SelectType = ' +@CodeRevTypeSt + ' AND SelectDate = ''' + @TodaySt + '''' + ' ORDERBY NEWID())'execute sp_executesql @SQLStringMy goal is to get a random percentage of records.The full SP follows. In a nutshell - I pull a set of records fromFD__Restart_Prog_Admit into a temporary table called FD__UR_Randoms.I need to retain the set of all records that COULD be eligible forselection. Based on the count of those records, I calculate how manyneed to be pulled - and then need to mark those records as "chosen".I'd just as soon not use the TMP_UR_Randoms table - I went that routebecause I ran into trouble with a #Tmp table in the above SQL.Can anyone help with this? Thanks in advance.Full SQL:CREATE PROCEDURE TP_rURRandomReview @ReviewType varchar(30)--Review type will fill using Crystal Parameter (setting defaults)AS/* 6.06.2007UR Requirements:(1) Initial 4-6 month review: 15% of eligible admissions(eligible via days in program and not yet discharged) must be reviewed4-6 months after admission. This review will be done monthly -meaning we'll have a moving target of names (with overlaps) whichcould be pulled from each month. (Minimum 5 records)(2) Subsequent 6-12 month review: Out of those already reviewed(in #1), we must review 25% of them (minimum of 5 records)(3) Initial 6-12 month review: Exclude any included in 1 or 2 -review 25% of admissions in program from 6-12 months (minimum 5)*/DECLARE @CodeRevType intDECLARE @PriorRec int -- number of records already markedeligible (in case user hits button more than once on same day for sametype of review)DECLARE @CurrRec int --number of eligible admitsDECLARE @RequFiles intDECLARE @SQLString nvarchar(1000)DECLARE @RequFilesSt varchar(100)DECLARE @CodeRevTypeSt char(1)DECLARE @TodayNotime datetimeDECLARE @TodaySt varchar(10)--strip the time off todaySELECT @TodayNotime = DateAdd(day,datediff(day,0,GetDate()),0)--convert the review type to a codeSelect @CodeRevType = Case @ReviewType when 'Initial 4 - 6 Month' then1 when 'Initial 6 - 12 Month' then 2 when 'Subsequent 6 - 12 month'then 3 END--FD__UR_Randoms always gets filled when this is run (unless it waspreviously run)--Check to see if the review was already pulled for this recordSELECT @PriorRec = (Select Count(*) FROM FD__UR_Randoms whereSelectType = @CodeRevType and SelectDate = @TodayNotime)If @PriorRec 0 GOTO ENDThis--************************************STEP A: Populate FD__UR_Randomstable with records that are candidates for review************************If @CodeRevType = 1BEGININSERT INTO FD__UR_Randoms (Admit_DOCID, Client_ID, SelectDate,SelectType,RecordChosen)(SELECT pa.OP__DOCID, pa.Client_ID,Convert(varchar(10),GetDate(),101) as SelectDate, @CodeRevType, 'F'FROM dbo.FD__RESTART_PROG_ADMIT paInner join FD__Client cOn pa.Client_ID = c.Client_IDWHERE Left(c.Fullname,2) <'TT' AND (Date_Discharge IS NULL)AND(DATEDIFF(d, Date_Admission, GETDATE()) 119)AND (DATEDIFF(d, Date_Admission, GETDATE()) <= 211)AND pa.OP__DOCID not in (Select Admit_DOCID from FD__UR_Randomswhere RecordChosen = 'T'))ENDIf @CodeRevType = 2--only want those that were selected in a batch 1 - in program 6-12months; selected for first reviewBEGININSERT INTO FD__UR_Randoms (Admit_DOCID, Client_ID, SelectDate,SelectType,RecordChosen)(SELECT pa.OP__DOCID, pa.Client_ID,Convert(varchar(10),GetDate(),101) as SelectDate, @CodeRevType, 'F'FROM dbo.FD__RESTART_PROG_ADMIT paInner join FD__Client cOn pa.Client_ID = c.Client_IDWHERE Left(c.Fullname,2) <'TT' AND (Date_Discharge IS NULL)AND(DATEDIFF(d, Date_Admission, GETDATE()) 211)AND (DATEDIFF(d, Date_Admission, GETDATE()) < 364)AND pa.OP__DOCID in (Select Admit_DOCID from FD__UR_Randomswhere SelectType = 1 AND RecordChosen= 'T'))ENDIf @CodeRevType = 3--only want those that were not in batch 1 or 2 - in program 6 to 12monthsBEGININSERT INTO FD__UR_Randoms (Admit_DOCID, Client_ID, SelectDate,SelectType,RecordChosen)(SELECT pa.OP__DOCID, pa.Client_ID,Convert(varchar(10),GetDate(),101) as SelectDate, @CodeRevType, 'F'FROM dbo.FD__RESTART_PROG_ADMIT paInner join FD__Client cOn pa.Client_ID = c.Client_IDWHERE Left(c.Fullname,2) <'TT' AND (Date_Discharge IS NULL)AND(DATEDIFF(d, Date_Admission, GETDATE()) 211)AND (DATEDIFF(d, Date_Admission, GETDATE()) < 364)AND pa.OP__DOCID NOT in (Select Admit_DOCID from FD__UR_Randomswhere SelectType < 3 AND RecordChosen= 'T'))ENDSELECT @CurrRec = (Select Count(*) FROM FD__UR_Randoms whereSelectType = @CodeRevType and SelectDate = @TodayNoTime)--*************************************STEP B Pick the necessarypercentage **************************************--if code type = 1, 15% otherwise 25%If @CodeRevType = 1BEGINSELECT @RequFiles = (@CurrRec * .15)ENDELSEBEGINSELECT @RequFiles = (@CurrRec * .25)END--make sure we have at least 5If @RequFiles < 5BEGINSELECT @RequFiles = 5End--*************************************STEP C Randomly select thatmany files**************************************--convert all variables to stringsSELECT @RequFilesSt = Convert(Varchar(100),@RequFiles)SELECT @CodeRevTypeSt = Convert(Char(1),@CodeRevType)SELECT @TodaySt = Convert(VarChar(10),@TodayNoTime,101)SELECT @SQLString = N'INSERT INTO TMP_UR_Randoms(Admit_DOCID,Client_ID, SelectDate, SelectType,RecordChosen)'SELECT @SQLString = @SQLString + N'(SELECT TOP ' + @RequFilesST + 'Admit_DOCID, Client_ID, SelectDate, SelectType, RecordChosen FROMFD__UR_Randoms 'SELECT @SQLString = @SQLString + N'WHERE SelectType = ' +@CodeRevTypeSt + ' AND SelectDate = ''' + @TodaySt + '''' + ' ORDERBY NEWID())'print @SQLStringexecute sp_executesql @SQLStringSELECT * FROM TMP_UR_Randoms/*--This select statement gives me what i want but I need to somehowmark these records and/or move this subset into the temp tableSelect Top @RequFilesFROM FD__UR_RandomsWHERE SelectType = @CodeRevType and SelectDate =Convert(varchar(10),GetDate(),101))ORDER BY NewID()*/ENDTHIS:GO

View 3 Replies View Related

SQL Server 2012 :: Return Random Records In A Table-valued Function?

Dec 19, 2013

My overarching goal is to generate sets of random Symptom records for each Enrollee in a drug study, so that for each cycle (period of time), the code will insert a random number of random records for each enrollee.

I'm trying to return a number of random records from a table, but inside a table-valued function... (which could be my problem).

CREATE FUNCTION dbo.ufn_GetTopSymptoms (
@enrollID INT
, @CTCVersion VARCHAR(20)
, @NumRecords INT
)
RETURNS TABLE

[Code] ....

But that ORDER BY NEWID() clause is illegal apparently, because here's the error it throws:

Msg 443, Level 16, State 1, Procedure ufn_GetTopSymptoms, Line 13
Invalid use of a side-effecting operator 'newid' within a function.

I was hoping I could return a set of enrollmentIDs and then use CROSS APPLY to generate a random set of records for each enrollmentID... is this not possible with APPLY? I was trying to avoid using a cursor...

The idea is basically to create all the Symptom records for all the patients in treatment cycle at once by using Enrollee OUTER APPLY dbo.ufn_GetTopSymtoms(dbo.Enrollment.EnrolleeID)

but that's clearly not working. Is there a way to do this without resorting to a cursor?

View 9 Replies View Related

Returning Random Records And NOT Similar (random Questions)

Jul 20, 2005

Hi,I need to extract randomly 5 records from the table "Questions". Now I useSELECT TOP 5 FROM Questions ORDERBY NEWID()And it works. The problem is that I need an additional thing: if SQLextracts record with ID=4, then it should not extract record with ID=9,because they are similar. I mean, I'd like something to tell SQL that if itextracts some questions, then it SHOULD NOT extract other ones.How can I do it?Thanks!Luke

View 1 Replies View Related

URGENT - Random 10 From Random 20 (2 Tbls)

Oct 14, 2004

I'm using ASP and SQL Serv 2000. What I need to get from 2 tables (company & customers) is random 10 customers from random 20 comp.
Anyone got an idea how to do this??? I've spent 2 days trying to get stored proc. or T-SQL to work, but nothing good came out of it. I can get 1 comp and 10 cust, but not a grouped list of 20 comp. w/ 10 cust. each.

Help is greatly appreciated.

View 1 Replies View Related

Random Row

Jul 20, 2005

Hi there.I need to fetch ONE random row from many. How can i get it? I try toexecute "SELECT field.table FROM table ORDER by RAND()" no effect.Thank you.

View 1 Replies View Related

Select Random Row In Sql

Apr 11, 2007

Hi,
i wanna fetch random data using sql query. is there any query that returns random row? Please help me.. i found some but they didnt work..

View 8 Replies View Related

How To Do A Random Select

Nov 10, 2000

Hy,
I nead to make a stored procedure in order to add a random record set.
This record set is used to write in an ASP page a list which is automatically modified everytime we reload the page.

Thanks !

View 1 Replies View Related

Random Records

Nov 16, 1999

Hi,

I'm trying to use the following query to select two random records from my database. Do you have any ideas of why the recrand field will not change? I am using MS Sql server 7.. Please email mark@dtdesign.com ..Cheers Mark

SELECT TOP 2 mytable.id AS RECID, RAND(mytable.id) AS recrand
FROM mytable
ORDER BY recrand

View 3 Replies View Related

DTS Bug? (or Random Feature?)

Jul 16, 1999

Has anyone noticed that if you created DTS package and try to
change connection properties (i.e. change DSN or redirect
DTS to different server or Database), as soon you click OK
it does not save new password and hence does not work
anymore. In my case to move Database from Development to
Production server I would have to recreate all DTS packages.
Is there any way around it?

Any ideas greatly appreciated.

View 1 Replies View Related

Random Numbers.

Jun 22, 2001

I am trying to get random numbers to have a unique value for different processes, then I can identify each process. What happens is that I use rand() function without seed, so I got my random numbers, but after shutting down SQLServer and try to get again another random number after booting up, the same series of random numbers is given again and again. So if anyone knows how I can get unique values,even though reseting the server, and using random function or any other method which automatically provides unique values,I'll really appreciate it if you let me know it.

This is the function: select rand()

Alberto.

View 2 Replies View Related

Random Values

Dec 24, 2001

Is there a way to write an SQL statement to choose random values from a particular select statement..for example:
select * from address
I was thinking, if there was a way to use an include statement for it like:
select * from address where id IN ('generates some random values')

thanks in advance

View 2 Replies View Related

Last Day In A Random Month

Mar 7, 2006

So i've got to generate these queries that go from the first of a one month to the last day of a month. the user provides the starting and ending months.

What I was wondering was is there an easy way to set the last day of the month in sql without having to go in and hard code which months end on the 30 and which ones end on the 31.

View 2 Replies View Related

Random Values In MS SQL,

Jan 1, 2005

Hello guys , I am new here,

Well, I am moving my greetings script from MS Access to MS SQL, here is what I was using in MS Access.

See this screenshot: Click Here
Well, I've imported the data from access database, but I don't know how to do the AutoNumber in MS SQL,

Also I don't know how can I add that Random thing *See the arrow in the screenshot*

Thanks in advance

View 2 Replies View Related

Random Varchar(10)

Jan 27, 2006

How can I have display random value for field varchar(10).

View 5 Replies View Related

Unique Random Row Id

May 4, 2006

I once came across a database in which when ever a row was inserted, a unique random code was also inserted in a column. This code generated was similar to format like {8A5FE5F1-6BDA-476C-A4DB584A7710FBF91121054625}. I was told that SQL2000 has some inbuilt functionality for this.

Any idea on how to do this using SQL2000 or coding.
I feel this is much better than Identity Column as using autonumbers in quesrystring is too much risky as they easily readable.

Please help.
Thanks

View 1 Replies View Related

Random Values

Mar 8, 2005

I have a table with 3 fields SiteID (PK), SiteCode, SiteName.
For each SiteCode I have several rows with different SiteName.
For example: 1 327 a
2 327 b
3 327 c
4 328 aa
5 328 bb......

I need to retrieve each time SiteCode with random SiteName.
For example: 327 b , 327 a , 327 c
328 aa 328 bb 328 aa.

I need it very urgent, so any ideas will be very helpful. Thanks to all,

View 1 Replies View Related

Random Select

Nov 23, 2007

How Can I select a Random set of records from a database table?

View 3 Replies View Related

Random From List

Jan 9, 2004

I have a customer that wants to be able to generate a random list...
-----------------------
The list is case numbers, and I can get those easy enough by saying

SELECT
dbo.table_case.id_number
FROM
dbo.table_case


Now, what I want to do is take that list and extract 1 out of every 1000, picking out random id_numbers to display.


Is this something I can do via a SQL query?

Thanks,
Dan

View 1 Replies View Related

How I Get The Random Row From The Table?

Jan 26, 2004

When I execute the following query several times, I get the same row if there is no new data inserted:

SELECT TOP 1 * FROM TableName

Is there a way to get a random row from the table? Thanks in advance.

View 14 Replies View Related

Random Insertion

Jun 10, 2008

Hi Experts ,
I want to insert datas randomly to all columns of a table.The columns have different datatypes like int,varchar,datetime. What to do??? It is urgent so please help.


TIA

RKNAIR

View 2 Replies View Related

Random Insertion

Jun 10, 2008

Hi Experts ,
I want to insert datas randomly to all columns of a table.The columns have different datatypes like int,varchar,datetime. How to create a procedure for the same??? please help.


TIA

RKNAIR

View 1 Replies View Related

Random Number

Apr 15, 2002

Generates a true random number from xxx to zzz. Uses a table variable so it all depends on the boundaries you specify how long it will take.

create procedure random_number
@lower int = 0,
@upper int = 256,
@number int = null output
as
set nocount on

declare @numbers table (number_id int identity(1,1), value int)

if @lower > @upper
begin
set @number = @lower
set @lower = @upper
set @upper = @number
end

set @number = rand((datepart(mm, getdate()) * 100000) + (datepart(ss, getdate()) * 1000) + datepart(ms, getdate()))

while (select count(*)
from @numbers) < (@upper - @lower + 1)
begin
insert into @numbers (value)
select (@upper - @lower + 1) * rand() + @lower
end

select @number = value
from @numbers
order by newid()
go

View 16 Replies View Related

Random String

Apr 15, 2002

I used this to generate a random password. You can change what it returns to up to an 8000 character password if you feel brave. You will need this function (http://www.sqlteam.com/Forums/topic.asp?TOPIC_ID=14924) to generate the random numbers. For some reason, occassionaly a NULL (CHAR(0)) character would get in there and mess things up so I had to remove those. You could change this to even include the non alpha numeric characters.

create procedure random_password
@length smallint,
@password nvarchar(256) = null output
as
set nocount on

declare @number int
declare @lower int
declare @upper int
declare @part tinyint

if @length > 256 set @length = 256
set @password = ''

while len(@password) < @length
begin
exec random_number 0, 3, @part output

if @part = 0
select @lower = ascii('a'),
@upper = ascii('z')
else if @part = 1
select @lower = ascii('A'),
@upper = ascii('Z')
else if @part = 2
select @lower = ascii('0'),
@upper = ascii('9')

set @part = null
set @number = null
exec random_number @lower, @upper, @number output
set @password = @password + ltrim(char(@number))
if substring(@password, len(@password), 1) = char(0) set @password = left(@password, len(@password) - 1)
end
go

View 3 Replies View Related

Output One Random Value From Same Name

Aug 22, 2013

I have a table

IDCODENAME
611GI08Gian
610GI07Gian
618GI15Gian
620 FT Rope
320 ST Soler
345 ST01 Soler

I need the output one random value from same name

like
IDCODENAME
611GI08Gian (it should be random)
620 FT Rope
320 ST Soler (it should be random)

View 7 Replies View Related

Random Number

Oct 8, 2005

I need to update an integer column in my table with a random number. Here's what I've done so far (with the table name and column names changed):

UPDATE dbo.MyTable
SET Column1 = RAND() * 1000000

My question is, how come the values in my column all have the same value? I thought the RAND function gives out a random number? How can I update my table to generate random numbers?

Thanks in advance.

View 3 Replies View Related

Random List

Dec 11, 2006

Hi -

I am new to TSQL and any help on the following would be appreciated.

I have a table that looks like this
security Message
2345 Good
2346 Good
uoas Bad
fsaf More
sdad More
asdd More
ndgs More

I have to pull in a list of distinct messages with a count and any 3 cusips that belong to the message.

I have written, something like this


SELECT MESSAGE_TEXT, COUNT(*) AS Expr1, MIN(security) AS Expr2, MAX(SECURITY) AS Expr3
FROM dbo.DerivedSIACDataMessages
GROUP BY MESSAGE_TEXT
ORDER BY COUNT(*) DESC

However, this lets me pull only 2 securities per message and I want to pull in 4 cusips.

Any help would be apprecioated

Thanks.

View 4 Replies View Related

Get Random Records..how ? Please

Feb 10, 2007

Hi every one.How can I get random 4 records in my table.
Example I want to get top 4 random records
Select top 4 from tbl_Products.....?
Thanks in appreciate

View 12 Replies View Related

More Complex Random Example

Dec 17, 2007

Hi all!
I have a table with three columns: Identity, DateTime (current_timestamp) and one which I want to fill with random values always depending on the value in the same column one row above.

Since I want it to be a stored procedure I have to pass three parameters - an initial value, the range within the random number is higher or lower than the number in the preceding row and the number of rows which should be inserted. This means that as soon as a new row is inserted there is also a new seed for the random value for the next line.

My problem now is that I would always get out the same number. Maybe you know a solution for my problem.

Many thanks and greetings from Austria

Landau

View 2 Replies View Related

Selecting A Random Row

Mar 4, 2008

Im trying to write a statement that only selects one of the possible rows that could be given.

For example:

Car ID: Colours Available:
1 Blue
1 Green
1 Black


I want the statement to return:

Car ID: Colours Available:
1 Blue(Random Selection)

Is this possible?

Thanks

View 20 Replies View Related

Random Numbers

Mar 19, 2008

Hi,

I have an int column that i want to have random numbers inserted into it.
How can I create random integer numbers to insert into my column?

Thanks

Whisky-my beloved dog who died suddenly on the 29/06/06-I miss u so much.

View 3 Replies View Related

Hot To Random ORDER?

Dec 1, 2007



I want to have a SELECT statement in stored procedure to make a random ORDER every time it runs, so one time ORDER BY first_name, then maybe person_telephone, then maybe per created_date, etc..

View 1 Replies View Related

Random Errors

Jan 4, 2006

Can anyone tell my why I'm getting these first few errors?  IT seems to be preventing my SQl Agent from successfully firing off my SSIS package:

 

01/04/2006 09:53:48,,Warning,[396] An idle CPU condition has not been defined - OnIdle job schedules will have no effect
01/04/2006 09:53:48,,Warning,[260] Unable to start mail session (reason: No mail profile defined)
01/04/2006 09:53:48,,Information,[129] SQLSERVERAGENT starting under Windows NT service control
01/04/2006 09:53:48,,Error,[364] The Messenger service has not been started - NetSend notifications will not be sent

View 4 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved