How To Assign Random Number To One Column For 500 Records?
Aug 4, 2005
I try to set up a testing sample table which contain one integer project_ID field for table Sample around 500 records, and want the project_ID to be random number within 1 to 99, how to implement script todo it?
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
First, I have that code whenever i disregard the "having ranges<=3" it selects record but when I include it it returns error. The problem is I want to just select records with ranges less than 3 miles..how do I do that.. and I want to count the number of selected rows and store it on a column on the same table.
I have a transformation where final result set give me 25 rows of data. Now before I put into destination table, I need to add another column which will show how many total records we have. Like.
My dataset:
A Â 20 abc B 24 mnp c 44 apq
Now I need to add another column within my transformation before I store the result set to destination like this:
A 20 abc 3 b 24 mnp 3 c 44 apq 3
Here. new column gives count of total rows in our dataset which was 3.
How can I achieve this? Can I use derive column to this?
I am new to SQL Server (coming from Oracle background) and have a large table I need to loop thru and assign a number 1 thru 5 on each record.
below is an example of how I would do it in Oracle.
declare num number := 1; cursor c_rec is SELECT rowid, t.* FROM temp t order by t.column; begin for d_rec in c_rec loop update temp set column = to_char(num)
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?
i have an application that uses a table for login access, for security reason i need to get a random numbers in this table daily. table consist of just two columns, userid and password. This table will be printed out on the web for users to get valid username and pw daily. I m thinking about a job or dts package that will run once daily with a sql script to generate random number (referable 5 digit-letters and numbers), delete the table and re-create the table with same set column names and insert the random values in username and pw column. Will appreciate help on this
How to create random number for the value in other colum. Please help and urgent
I have a table with 4 column ( ID, Ori_Quantity, Rand_Quantity, Location)
If Ori_quantity < 5000 then Rand_quanty as qty = I want Random number within 100 Else If Ori_quantity = 0 or < 10 then Rand_quanty as qty = I want Random number within 7 End if
From tblname where Location = 'DAS'
I have around 2500 field. So when I run the query I expect the result should be like below
In a Name table, I need to generate unique 6 digit random numbers in a field called UniqueID for all records that have the ID field populated. I will need to run this script periodically. It is critical that any prevoiusly assigned UniqueIDs do not change and only fields that have an empty UniqueID field are updated. I need to preserve the historical mapping of the existing IDs to the ongoing assignment of UniqueIDs.
Here is my issue. I have a list of merchants (generated daily) and Ineed to assign them eually to a set of analysts. Both the merchantlist and analyst list can change daily. I want to assign each merchantwith an analyst daily and need help to write out a stored procedurefor this (do not want to use VB).Here is relevant code for the tables:CREATE TABLE MerchList (MerchListID int IDENTITY (1, 1) NOT NULL ,FileDate datetime NOT NULL ,MerchID int NOT NULL ,AnalystID int NOT NULL ,)CREATE TABLE tblAnalyst (AnalystID int IDENTITY (1, 1) NOT NULL ,AnalystName varchar(100) NOT NULL)there will be about 10000 records in table MerchList and around 25records in table tblAnalyst.This will be used to assign work to analysts on a daily basis.Thanks for all your help!Vishal
I have Logs table and want to assign a serial number to the techs using the following query
Select Date, Case_ID, Site, Dept, Tech, Start_Time, ROW_NUMBER () OVER (PARTITION BY Date, Site, Dept, Tech ORDER BY Start_Time) as Row_Num FROM Logs Where Date = Getdate()
I get the following results.
Date Case ID Site DeptTechStart TimeRow_Num 7/28/14 10023 TartvilleMaintcAmy P.7:301 7/28/14 56789 TartvilleMaintcRem W.8:051 7/28/14 23098 TartvilleMaintcAmy P.8:352 7/28/14 70004 TartvilleMaintcAmy P.9:103 7/28/14 12708 TartvilleMaintcMag O.10:001 7/28/14 10004 TartvilleMaintcAmy P.12:304 7/28/14 40056 TartvilleServiceJoe F.7:301 7/28/14 23458 TartvilleServiceJoe F.7:552 7/28/14 69200 TartvilleServiceRus T. 7:301
Please notice the cases in Maintc department. See how Amy P.'s shift is broken by Rem W. and Mag O. But the Row Number does not recognize this, it still says Amy P's case as 2 and 4 the even though Rem's and Mag's cases were in between.
This is what I really wanted.
Date Case ID Site DeptTechStart TimeRow_Num 7/28/14 10023 TartvilleMaintcAmy P.7:301 7/28/14 56789 TartvilleMaintcRem W.8:051 7/28/14 23098 TartvilleMaintcAmy P.8:351 7/28/14 70004 TartvilleMaintcAmy P.9:102 7/28/14 12708 TartvilleMaintcMag O.10:001 7/28/14 10004 TartvilleMaintcAmy P.12:301 7/28/14 40056 TartvilleServiceJoe F.7:301 7/28/14 23458 TartvilleServiceJoe F.7:552 7/28/14 69200 TartvilleServiceRus T. 7:301
I tried many combination of columns for Partition by () and Order by () and the best I can get is the result at the top. How should I achieve it.
I need to generate a random 10 digit alphanumeric string that is also unique within a table. My application will be calling a stored procedure to insert this number into the table. This number will be associated with a id from another table. Is it better to generate the random number within sql (and perform the lookup at the same time), then just pass the number back to the calling application ?
If the calling application generates the number, it will also need to make a call to check if its unique. So im thinking it would be best to simply have sql generate this random number, check the number against the table and then insert the new record.
ID  Item           RandomNumber ------------------------------------------- 1   JEANS                   1234567 2   SHIRT                 72813550 3   HOOD                           Null 4   TROUSER             72191839 5   BLAZER                            0
I want to perform a query so that SQL should look for RandomNumber Values and set a Unique Random Number Where RandomNumber Value is Null or 0.So I have got a solution as one of the MSDN Member shared the below query
select id,item,RandomNumber=Case when RandomNumber=0 then (select floor(rand()*100000000-1)) when RandomNumber is null then (select floor(rand()*100000000-1)) else RandomNumber end from tblProducts
So, can you all confirm me, that performing this query ensures that if a Value is assigned to one of the Item in RandomNumber Column, that value will not be assignend to any other Item in RandoNumberColumn.
Hey Guys, I have a quick stored procedure question for you. I created a procedure that returns a randomly generated number.
I know there is a built in Rand() function but I need to be able to specify the range. Anyways, it€™s returning multiple numbers (1 for each row in the tempTable) But I just want one number returned. I tried using MAX( ) but that€™s not a good way of doing it.
My question is, how do I return just one record or number?
Thanks Fellas,
Chris
ALTER PROCEDURE dbo.spx_GetRandomNum
AS
DECLARE @Start_Num int
DECLARE @End_Num int
DECLARE @ReturnValue int DECLARE @RecNum int DECLARE @CurrentRec int DECLARE @MyCount int
SET @Start_Num=1
SET @End_Num=100
CREATE TABLE #tblTemp (CurrentRecNo int IDENTITY(1,1), RandomNumber int null)
SET @MyCount = ( @End_Num - @Start_Num ) + 1 SET @CurrentRec = 1
WHILE @CurrentRec <= @MyCount
BEGIN SET @RecNum = CAST((RAND() * @MyCount) AS int) + @Start_Num
INSERT INTO #tblTemp (RandomNumber) VALUES (@RecNum) SET @CurrentRec = @CurrentRec + 1
END
SET @ReturnValue = (SELECT RandomNumber FROM #tblTemp)
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
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
hi again, i just want to ask if how can i randomly select 5 distinct records from a table w/ a hundreds of records everytime i exec a stored procedure?? thanks
hi im creating 2 random numbers, matching one of them (i) to the QuestionsNo column in my database, and then making it display the whole record. the code below generate 2 random numbers but i cannot get the rest of it to work. i need it to match the random number to the QuestionNo field in my database and display the whole record. can anyone help me and tell me where im going wrong please????
Dim i,j as integer Randomize i = CInt(Int((10 * Rnd()) + 1)) j = CInt(Int((10 * Rnd()) + 1)) example.InnerHtml = "Random Number : " & i example1.InnerHtml = "Random Number : " & j
strSQL = "SELECT * FROM Table1 WHERE QuestionNo = " & i &""
I downloded the random record script from swynk site and when I run It gives me error msg
Server: Msg 170, Level 15, State 1, Procedure PROC_RANDOM, Line 73 Line 73: Incorrect syntax near 'DECLARE CUR_MEU CURSOR SCROLL FOR SELECT TOP '. Server: Msg 170, Level 15, State 1, Procedure PROC_RANDOM, Line 101 Line 101: Incorrect syntax near 'DECLARE CUR_MEU CURSOR SCROLL FOR SELECT TOP '.
Can anyone guide me
I've copied the script
Thanks.
CREATE PROCEDURE PROC_RANDOM @VEZES INT , @TABELA CHAR(50) , @CAMPO CHAR(50) , @REPETIR CHAR(1) = "S" AS
-- DECLARATION OF VARIABLES DECLARE @CONTADOR INT , @VAL INT , @AUX CHAR(10) DECLARE @TOTAL INT , @VALOR INT DECLARE @NAME CHAR(50)
-- NO MESSAGES SET NOCOUNT ON
-- CHECK FOR THE TABLE CALLED 'RETORNO' IF EXISTS (SELECT * FROM DBO.SYSOBJECTS WHERE ID = OBJECT_ID(N'[DBO].[RETORNO]') AND OBJECTPROPERTY(ID, N'ISUSERTABLE') = 1) DROP TABLE [DBO].[RETORNO]
-- CREATES THE TABLE
CREATE TABLE RETORNO ( CAMPO CHAR(50) )
-- IF THE USER DON'T WANT SAME RESULTS , CREATE A TEMPORARY TABLE IF @REPETIR = 'N' BEGIN CREATE TABLE #ALE ( COD INT ) END
-- GET THE TOTAL NUMBER OF RECORDS , USING THE SYSINDEXES TABLE SELECT @TOTAL = ROWS FROM SYSINDEXES WHERE ID = object_ID(@TABELA) AND INDID < 2
-- IF THERE IS A TABLE.... IF @TOTAL IS NOT NULL BEGIN
-- CLEAN THE COUNTER SELECT @CONTADOR = 0
-- DO A LOOP SEVERAL TIMES TO GET THE NUMBER , AND RECORDS , OF RANDOM RECORDS THAT THE USER WANT WHILE @CONTADOR <> @VEZES BEGIN
-- INCREASE THE COUNTER SELECT @CONTADOR = @CONTADOR + 1
-- GET A RANDOM NUMBER USING THE DATE.... SELECT @VAL = REVERSE((DATEPART(mm, GETDATE()) * 100000 ) + (DATEPART(ss, GETDATE()) * 1000 ) + DATEPART(ms, GETDATE()))
SELECT @AUX = CONVERT(CHAR,@VAL * ( @CONTADOR ) )
SELECT @AUX = REVERSE(SUBSTRING(@AUX,3,5))
SELECT @VALOR = (CONVERT(INT,@AUX)%@TOTAL)+1
-- IF THE USER DON'T WANT TO REPEAT DATA... IF @REPETIR = 'N' BEGIN -- CHECK FOR THE USE OF THIS NUMBER IF NOT EXISTS(SELECT COD FROM #ALE WHERE COD = @VALOR) BEGIN
-- CREATE A DYNAMIC CURSOR WITH SOME RECORDS. THE LAST WILL BE THAT RANDOM EXECUTE("DECLARE CUR_MEU CURSOR SCROLL FOR SELECT TOP " + @VALOR + " " + @CAMPO+ " FROM " +@TABELA )
OPEN CUR_MEU
-- GO TO THE LAST RECORD FETCH LAST FROM CUR_MEU INTO @NAME
-- INSERT THE DATA IN THE RETURN TABLE INSERT INTO RETORNO VALUES(@NAME)
CLOSE CUR_MEU
DEALLOCATE CUR_MEU
-- STORE THE RANDOM NUMBER IN A TABLE TO AVOID THE USE OF THIS NUMBER AGAIN INSERT INTO #ALE VALUES(@VALOR)
END ELSE BEGIN -- IF THIS NUMBER WAS USED THEN DECREASE THE COUNTER AND TRY AGAIN... SELECT @CONTADOR = @CONTADOR - 1 END
END ELSE BEGIN -- CREATE A DYNAMIC CURSOR WITH SOME RECORDS. THE LAST WILL BE THAT RANDOM EXECUTE("DECLARE CUR_MEU CURSOR SCROLL FOR SELECT TOP " + @VALOR + " " + @CAMPO+ " FROM " +@TABELA )
OPEN CUR_MEU
-- GO TO THE LAST RECORD FETCH LAST FROM CUR_MEU INTO @NAME
-- INSERT THE DATA IN THE RETURN TABLE INSERT INTO RETORNO VALUES(@NAME)
CLOSE CUR_MEU
DEALLOCATE CUR_MEU
END
END
SET NOCOUNT OFF END
-- IF THE TABLE WAS CREATED , WE MUST DROP IT IF @REPETIR = 'N' BEGIN DROP TABLE #ALE END
-- RETURN TO THE USER ALL RANDOM RECORDS SELECT CAMPO FROM RETORNO
-- DROP THE TABLE WITH THE RANDOM RECORDS DROP TABLE RETORNO
I need a way to select records at random from a SQL Server 2000 table. If the record I've selected at random meets a few simple conditions (column X <> 'A' and column Y == 'Z') then return this record and get the next. Ideally I'd be able to do this in a stored proc where I'd call it with:
parameter 1: table name parameter 2: number of random records to get parameter 3: value for condition 1 parameter 4: value for condition 2
I downloded the random record script from swynk site and when I run It gives me error msg
Server: Msg 170, Level 15, State 1, Procedure PROC_RANDOM, Line 73 Line 73: Incorrect syntax near 'DECLARE CUR_MEU CURSOR SCROLL FOR SELECT TOP '. Server: Msg 170, Level 15, State 1, Procedure PROC_RANDOM, Line 101 Line 101: Incorrect syntax near 'DECLARE CUR_MEU CURSOR SCROLL FOR SELECT TOP '.
Can anyone guide me
I've copied the script
Thanks.
CREATE PROCEDURE PROC_RANDOM @VEZES INT , @TABELA CHAR(50) , @CAMPO CHAR(50) , @REPETIR CHAR(1) = "S" AS
-- DECLARATION OF VARIABLES DECLARE @CONTADOR INT , @VAL INT , @AUX CHAR(10) DECLARE @TOTAL INT , @VALOR INT DECLARE @NAME CHAR(50)
-- NO MESSAGES SET NOCOUNT ON
-- CHECK FOR THE TABLE CALLED 'RETORNO' IF EXISTS (SELECT * FROM DBO.SYSOBJECTS WHERE ID = OBJECT_ID(N'[DBO].[RETORNO]') AND OBJECTPROPERTY(ID, N'ISUSERTABLE') = 1) DROP TABLE [DBO].[RETORNO]
-- CREATES THE TABLE
CREATE TABLE RETORNO ( CAMPO CHAR(50) )
-- IF THE USER DON'T WANT SAME RESULTS , CREATE A TEMPORARY TABLE IF @REPETIR = 'N' BEGIN CREATE TABLE #ALE ( COD INT ) END
-- GET THE TOTAL NUMBER OF RECORDS , USING THE SYSINDEXES TABLE SELECT @TOTAL = ROWS FROM SYSINDEXES WHERE ID = object_ID(@TABELA) AND INDID < 2
-- IF THERE IS A TABLE.... IF @TOTAL IS NOT NULL BEGIN
-- CLEAN THE COUNTER SELECT @CONTADOR = 0
-- DO A LOOP SEVERAL TIMES TO GET THE NUMBER , AND RECORDS , OF RANDOM RECORDS THAT THE USER WANT WHILE @CONTADOR <> @VEZES BEGIN
-- INCREASE THE COUNTER SELECT @CONTADOR = @CONTADOR + 1
-- GET A RANDOM NUMBER USING THE DATE.... SELECT @VAL = REVERSE((DATEPART(mm, GETDATE()) * 100000 ) + (DATEPART(ss, GETDATE()) * 1000 ) + DATEPART(ms, GETDATE()))
SELECT @AUX = CONVERT(CHAR,@VAL * ( @CONTADOR ) )
SELECT @AUX = REVERSE(SUBSTRING(@AUX,3,5))
SELECT @VALOR = (CONVERT(INT,@AUX)%@TOTAL)+1
-- IF THE USER DON'T WANT TO REPEAT DATA... IF @REPETIR = 'N' BEGIN -- CHECK FOR THE USE OF THIS NUMBER IF NOT EXISTS(SELECT COD FROM #ALE WHERE COD = @VALOR) BEGIN
-- CREATE A DYNAMIC CURSOR WITH SOME RECORDS. THE LAST WILL BE THAT RANDOM EXECUTE("DECLARE CUR_MEU CURSOR SCROLL FOR SELECT TOP " + @VALOR + " " + @CAMPO+ " FROM " +@TABELA )
OPEN CUR_MEU
-- GO TO THE LAST RECORD FETCH LAST FROM CUR_MEU INTO @NAME
-- INSERT THE DATA IN THE RETURN TABLE INSERT INTO RETORNO VALUES(@NAME)
CLOSE CUR_MEU
DEALLOCATE CUR_MEU
-- STORE THE RANDOM NUMBER IN A TABLE TO AVOID THE USE OF THIS NUMBER AGAIN INSERT INTO #ALE VALUES(@VALOR)
END ELSE BEGIN -- IF THIS NUMBER WAS USED THEN DECREASE THE COUNTER AND TRY AGAIN... SELECT @CONTADOR = @CONTADOR - 1 END
END ELSE BEGIN -- CREATE A DYNAMIC CURSOR WITH SOME RECORDS. THE LAST WILL BE THAT RANDOM EXECUTE("DECLARE CUR_MEU CURSOR SCROLL FOR SELECT TOP " + @VALOR + " " + @CAMPO+ " FROM " +@TABELA )
OPEN CUR_MEU
-- GO TO THE LAST RECORD FETCH LAST FROM CUR_MEU INTO @NAME
-- INSERT THE DATA IN THE RETURN TABLE INSERT INTO RETORNO VALUES(@NAME)
CLOSE CUR_MEU
DEALLOCATE CUR_MEU
END
END
SET NOCOUNT OFF END
-- IF THE TABLE WAS CREATED , WE MUST DROP IT IF @REPETIR = 'N' BEGIN DROP TABLE #ALE END
-- RETURN TO THE USER ALL RANDOM RECORDS SELECT CAMPO FROM RETORNO
-- DROP THE TABLE WITH THE RANDOM RECORDS DROP TABLE RETORNO
Once again - My table should consist of 100 new records for a field MobilePhone(of char type) and last 5 digits should be randomly choosed (should be like this: +381randomno1randomno2.. etc.(example: +38156465, where '+' sign makes it char type and digits after +381 are randomly choosed. :confused: Anyone knows how to solve this....PLEASE?
I'm not sure if this is a completely dumb question, but please humor me:) I have a table of records, called Records, each of which has aCategory_ID that places it in a specific category; the details of thecategories are stored in another table called Category. What I need todo is retrieve a recordset that contains one record from each category,but where the records that are retrieved are random. I know how toretrieve one or more random records using "order by NewID()", but havenot been able to work out how to get one random record from eachcategory.Any assistance in this puzzler will be HUGELY appreciated!ThanksFEB