Select At Random Order From Database

Dec 23, 2005

Hi,

I need to select few items from sql database.I know for ORDER BY, but I need those items to be mixed in random order every time when they are returned from database. Those are the same items every time, just randomly mixed.

Can i do it with SQL, or I have to find another way (e.g. to mix them after sql returns them)?

View 1 Replies


ADVERTISEMENT

How Can Select Random Rows From Database?

Jan 23, 2008

Hi
Iam developing online test using ASP.NET,C#.NET.Now my doubt is test takers should get random questions from the database sqlserver2005.Already i ve inserted 10 question into the database.I ve used NEW ID() .But questions are repeating.I am new commer in to IT industry .Provide me with code.Given below is my code.I can retrive questions from the database now but cannot get in random order.protected void Page_Load(object sender, EventArgs e)
{Label10.Visible = false;
Label9.Visible = false;if (!IsPostBack)
{if (Session["id"] == null)
{Session["id"] = 1;
}Session["ans"] = 0;SqlConnection con = new SqlConnection(@"server=123-9181FF31362SQLEXPRESS;user id=sampleu;pwd=Sampleu2;database=n;");
con.Open();
SqlCommand cmd = new SqlCommand("select * from n3 where sno='" + Convert.ToInt16(Session["id"].ToString()) + "' ", con);SqlDataReader re;
re = cmd.ExecuteReader();while (re.Read())
{
 
Label1.Text = re[0].ToString();
Label2.Text = re[1].ToString();
Label3.Text = re[2].ToString();
Label4.Text = re[3].ToString();
Label5.Text = re[4].ToString();
Label6.Text = re[5].ToString();string sss = re[6].ToString();if (sss == "nil")
{
Panel1.Visible = true;Panel2.Visible = false;
}
else
{Panel1.Visible = false;Panel2.Visible = true;
}
}
re.Close();
}
}
 
 protected void Button1_Click(object sender, EventArgs e)
{string Answer = "";if (RadioButton1.Checked == true)
{Answer = "A";
}else if (RadioButton2.Checked == true)
{Answer = "B";
}else if (RadioButton3.Checked == true)
{Answer = "C";
}else if (RadioButton4.Checked == true)
{Answer = "D";
}else if (RadioButton5.Checked == true)
{Answer = "True";
}else if (RadioButton6.Checked == true)
{Answer = "False";
}SqlConnection con1 = new SqlConnection(@"server=123-9181FF31362SQLEXPRESS;user id=sampleu;pwd=Sampleu2;database=n;");
con1.Open();
string ss = Session["id"].ToString();SqlCommand cmd1 = new SqlCommand("select Answer from n3 where sno='" + Convert.ToInt16(Session["id"].ToString()) + "' ", con1);
SqlDataReader re1;string result1 = "";
re1 = cmd1.ExecuteReader();if (re1.Read())
{
result1 = re1[0].ToString();
}
//Session["ans"] = 0;if (Answer == result1)
{Session["ans"] = (Convert.ToInt16(Session["ans"].ToString()) + 1);
 
}
con1.Close();
 Session["id"] = (Convert.ToInt16(Session["id"]) + 1);
RadioButton1.Checked = false;RadioButton2.Checked = false;
RadioButton3.Checked = false;RadioButton4.Checked = false;
RadioButton5.Checked = false;RadioButton6.Checked = false;
 
 SqlConnection con = new SqlConnection(@"server=123-9181FF31362SQLEXPRESS;user id=sampleu;pwd=Sampleu2;database=n;");
con.Open();SqlCommand cmd = new SqlCommand("select * from n3 where sno='" + Convert.ToInt16(Session["id"].ToString()) + "' ", con);SqlDataReader re;
re = cmd.ExecuteReader();
 
 
 while (re.Read())
{
Label1.Text = re[0].ToString();
Label2.Text = re[1].ToString();
Label3.Text = re[2].ToString();
Label4.Text = re[3].ToString();
Label5.Text = re[4].ToString();
Label6.Text = re[5].ToString();string sss = re[6].ToString();if (sss == "nil")
{
Panel1.Visible = true;Panel2.Visible = false;
}
else
{Panel1.Visible = false;Panel2.Visible = true;
}
}
re.Close();int s = Convert.ToInt16(Session["id"].ToString());if (s == 11)
{
Label10.Text = Session["ans"].ToString() + " / " + "10";Label9.Visible = true;
Label10.Visible = true;
//int x = Convert.ToInt16(Session["ans"].ToString());
//int y = (x/10) * 100;//y = Label10.Text;
 
}
////// SqlConnection con6 = new SqlConnection(@"server=123-9181FF31362SQLEXPRESS;user id=sampleu;pwd=Sampleu2;database=n;");
////// con6.Open();
////// SqlCommand cmd6 = new SqlCommand("SELECT CONVERT(int, 10*RAND()) from n3 where sno='" + Convert.ToInt16(Session["id"].ToString()) + "' ", con6);
////// SqlDataReader re6;
////// re6 = cmd6.ExecuteReader();
////// //select top 5 * from Employee order by NEWID()
//////// SELECT FirstName,LastName
////////FROM Person.Contact
////////TABLESAMPLE SYSTEM (10 PERCENT)
 
////// while (re6.Read())
////// {
////// Label1.Text = re6[0].ToString();
////// }
////// con6.Close();
}
}

View 3 Replies View Related

How To Select Random Records From Database (advanced)

Mar 12, 2006

hello i have a problem and i dont know if it can fixed or not i'm using asp.net 2 and sqlserver 2005 i have a table named questions in the database and that table has 5 columns questionid,question,answer1,answer2,answer3 every questions has 3 answers 1 right and the other 2 are wrong what i want to do is select 10 random questions and their right and wrong answers show in my asp.net page as application the answers will be in radio buttons so is that can be done or it's not possible.thanks all

View 17 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

How To Make A Random Order Query ?

May 1, 2004

If we use: select * from ..... , normally, it will return an ordered result ( may be order by ID ), but how can we make an random order select statement. It mean every time we run the query, the result will be different from the other ?

View 1 Replies View Related

Selecting Records By Random Order

Sep 22, 2000

Hello,

I need to select records by random order everytime user go to that page. QuestionID is the uniq field in this table.

SELECT * FROM QuestionMaster.

I tried to use the following statement to get the random records but I can't get the value in the variable out of this statement that I can use in my above select statement. Please HELP.

SELECT Convert(int,RAND()*97)

Thanks in a million.

Sarika

View 1 Replies View Related

Random Order For Test Questions

Oct 26, 2007

Hello Everyone,
I am using sql server 2000 to create a test database. I have two tables, a table for questions and one for answers. I want to create random orders for the test questions and answers. I tried to use the rand function but that doesn’t seem to work, because when I order by the random number, the questions are still in the primary key order. My primary key is 'questioned'. Can someone help me out on how to randomly order my questions and ansers?


Select questionID ,Rand(Questionid)from tblTestQuestions
order by rand(questionID)


Thanks
GEM

View 7 Replies View Related

Sorting Matrix Column In Random Order

Aug 14, 2007



Hi,

I have a matrix report...the column results
are as follows

Con Std , Con Access, SF Std, SF Acc, Broadband, Pay TV

how would i make the columns appear in the above order when displaying as it is default alphetically sorted...I have tried putting numbers at the front which work till I get to the number 10 which alphetically sorted is next to 1 not 9?
is there a better way off sorting matrix column which have no specific criteria to sort from?

thanks

View 6 Replies View Related

Integration Services :: Importing Text File Into Table - Random Data Order

Aug 3, 2015

I'm importing comma-delimited text files into a SQL table. The data imports in a seemingly random order. One time I import and the lines appear one way and the next time I import they import another way.

Is there a way to force the text files to import in the same order the data is found in the file?

View 10 Replies View Related

Default Sort Order - Open Table - Select Without Order By

Mar 27, 2008

Hi!

I recently run into a senario when a procedure quiered a table without a order by clause. Luckily it retrived data in the prefered order.

The table returns the data in the same order in SQL Manager "Open Table"

So I started to wonder what deterimins the sort order when there is no order by clause ?

I researched this for a bit but found no straight answers. My table has no PK, but an identiy column.

Peace.

/P

View 5 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 Select

Nov 23, 2007

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

View 3 Replies View Related

SQL: Sequential Random Select

Mar 8, 2006

Hello--I need to create a SQl statement (SQL SERVER 2000) which will do the following:

read table1 sequentially
select every "nth" record
write each selected record to and output table

Your help is greatly appreciated.
thanks,
MB

View 3 Replies View Related

Select 10 Random Records

Apr 22, 2008

Hello,

Is it possible to select 10 random records from a table?

Thanks,
Miguel

View 1 Replies View Related

SELECT A Random Row For Each Different Type

Jul 20, 2005

Hello all,I'm using SS 2000Based on the following table and data:CREATE TABLE T (F1 VARCHAR(1),F2 INT,F3 INT)/* T has no unique key *//* The data */INSERT INTO TSELECT 'A' AS F1, 1 AS F2, 10 AS F3UNION ALLSELECT 'B', 2, 12UNION ALLSELECT 'B', 3, 11UNION ALLSELECT 'A', 4, 10UNION ALLSELECT 'B', 3, 11UNION ALLSELECT 'A', 0, 0UNION ALLSELECT 'B', 2, 5UNION ALLSELECT 'D', 6, 7In the real situation, T is a subquery build from some tables and views. Icannot easily send the real problem.I want a query that will return:- One row for each different F1, no matter which it is.- Ideally, no temporary table should be created. Only subquery.- F2 and F3 must come from the same row. So the use of aggregate functionsto retreive each of them cannot be used.A possible result could be:F1 F2 F3---- --------- -----------A 1 10B 2 12D 6 7How could I do that?Thanks for your helpYannick

View 2 Replies View Related

Select Random Records From MS SQL Table?

Aug 26, 2005

Hello,I have 1000 of records in my table. I wanna select random 100 of them? How?regards

View 3 Replies View Related

How Do I Select A Random Record From The Table

Sep 18, 2000

Hello,

I need to write a select statement where I need to select the record randomely. Is there any function to do that? What's the best way to do that? Please help...

Thanks in a million.

Sarika

View 1 Replies View Related

Select Random Row Based On Weights

Feb 9, 2007

I have a table with two columns: value and weight (weight is smallint).

I want a query that will return the value of one row at random with the added requirement that rows with a higher weight have a higher probability of being chosen. Any ideas?

View 4 Replies View Related

How To Select Random Row In Table Using Sql Server...

Jun 12, 2007

I Got the Sql query "Select Top 1 * from Books order by NewId()"........ for select Random row in a table .. any one can explain Above Query

Regards,

S.sajan

View 4 Replies View Related

Specify Order For Select Results, Order By: Help!

Nov 17, 2006

Lets say I have a table named [Leadership] and I want to select the field 'leadershipName' from the [Leadership] Table.

My query would look something like this:

Select leadershipName
From Leadership

Now, I would like to order the results of this query... but I don't want to simply order them by ASC or DESC. Instead, I need to order them as follows:

Executive Board Members, Delegates, Grievance Chairs, and Negotiators

My question: Can this be done through MS SQL or do I need to add a field to my [Leadership] table named 'leadershipImportance' or something as an integer to denote the level of importance of the position so that I can order on that value ASC or DESC?

Thanks,

Zoop

View 1 Replies View Related

Random Selection From Table Variable In Subquery As A Column In Select Statement

Nov 7, 2007

Consider the below code: I am trying to find a way so that my select statement (which will actually be used to insert records) can randomly place values in the Source and Type columns that it selects from a list which in this case is records in a table variable. I dont really want to perform the insert inside a loop since the production version will work with millions of records. Anyone have any suggestions of how to change the subqueries that constitute these columns so that they are randomized?




SET NOCOUNT ON


Declare @RandomRecordCount as int, @Counter as int
Select @RandomRecordCount = 1000

Declare @Type table (Name nvarchar(200) NOT NULL)
Declare @Source table (Name nvarchar(200) NOT NULL)
Declare @Users table (Name nvarchar(200) NOT NULL)
Declare @NumericBase table (Number int not null)

Set @Counter = 0

while @Counter < @RandomRecordCount
begin
Insert into @NumericBase(Number)Values(@Counter)
set @Counter = @Counter + 1
end


Insert into @Type(Name)
Select 'Type: Buick' UNION ALL
Select 'Type: Cadillac' UNION ALL
Select 'Type: Chevrolet' UNION ALL
Select 'Type: GMC'

Insert into @Source(Name)
Select 'Source: Japan' UNION ALL
Select 'Source: China' UNION ALL
Select 'Source: Spain' UNION ALL
Select 'Source: India' UNION ALL
Select 'Source: USA'

Insert into @Users(Name)
Select 'keith' UNION ALL
Select 'kevin' UNION ALL
Select 'chris' UNION ALL
Select 'chad' UNION ALL
Select 'brian'


select
1 ProviderId, -- static value
'' Identifier,
'' ClassificationCode,
(select TOP 1 Name from @Source order by newid()) Source,
(select TOP 1 Name from @Type order by newid()) Type

from @NumericBase



SET NOCOUNT OFF

View 14 Replies View Related

Reporting Services :: Select 10 Random Records From Past 30 Days For Each User

May 18, 2015

I have these columns. TicketID, User, Date...I want to select 10 random tickets for each user for the past 30 days. I not sure whether to do this via sql or using VB in the report design.

View 5 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

INSERT-SELECT Depending On The Select:ed Order

Aug 15, 2006

I'm doing a INSERT...SELECT where I'm dependent on the records SELECT:ed to be in a certain order. This order is enforced through a clustered index on that table - I can see that they are in the proper order by doing just the SELECT part.

However, when I do the INSERT, it doesn't work (nothing is inserted) - can the order of the records from the SELECT part be changed internally on their way to the INSERT part, so to speak?

Actually - it is a view that I'm inserting into, and there's an instead-of-insert trigger on it that does the actual insertions into the base table. I've added a "PRINT" statement to the trigger code and there's just ONE record printed (there should be millions).

View 3 Replies View Related

Recordset's Order And Database's Physical Order?

Jul 20, 2005

Hi,guys!I have a table below:CREATE TABLE rsccategory(categoryid NUMERIC(2) IDENTITY(1,1),categoryname VARCHAR(20) NOT NULL,PRIMARY KEY(categoryid))Then I do:INSERT rsccategory(categoryname) VALUES('url')INSERT rsccategory(categoryname) VALUES('document')INSERT rsccategory(categoryname) VALUES('book')INSERT rsccategory(categoryname) VALUES('software')INSERT rsccategory(categoryname) VALUES('casus')INSERT rsccategory(categoryname) VALUES('project')INSERT rsccategory(categoryname) VALUES('disert')Then SELECT * FROM rsccategory in ,I can get a recordeset with the'categoryid' in order(1,2,3,4,5,6,7)But If I change the table definition this way:categoryname VARCHAR(20) NOT NULL UNIQUE,The select result is in this order (3,5,7,2,6,4,1),and 'categoryname 'in alphabetic.Q:why the recordset's order is not the same as the first time since'categoryid' is clustered indexed.If I change the table definition again:categoryname VARCHAR(20) NOT NULL UNIQUE CLUSTEREDthe result is the same as the first time.Q:'categoryname' is clustered indexed this time,why isn't in alphabeticorder?I am a newbie in ms-sqlserver,or actually in database,and I do havesought for the answer for some time,but more confused,Thanks for yourkind help in advance!

View 2 Replies View Related

Random Failed Logins For Database

Mar 10, 2004

Hi,

We are running MSSQL 2000 on a reasonably powerful dedicated Win2k system Dual 2.4 Xeon Procs, 2 GB of RAM, Ultra 160 SCSI disks.. blah blah blah.

Our primary use this database server is for our Coldfusion Application servers. We host about 50 or so databases.

Of late, we have been experiencing random failed logins for certain databases. These failed logins are logged to the event log on the server. They randomly; queries executed against a datasource configured on our application servers trying to get data from the database fail with a login failure when other times they will succeed. I am confused about this issue. Could an issue where the SQL Server is overloaded cause a login failure for a database?


Errol Neal

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

Insert Random Data Into Database Tables

May 28, 2008



Hi all


I have blank tables and i want to fill tables with data but i have many tables and i need script or whatever automated this operation like loop

thanks in advance


View 5 Replies View Related

Select Top And Order By

Aug 24, 2007

If I return top 25 with an order by, will it get the whole result then take top 25 and order it or will it just return the first 25 it finds and order it. select top 25 c.firstname, c.lastname, o.units, o.partnum
from customer c
inner join orders o
on c.key = o.key
where o.units > 500
order by partnum 

View 1 Replies View Related

Order By With Select Into

Jul 20, 2005

I have a Microsoft SQL Server 7.0.I wrote a sql command that creates a temporary table with a ORDER BYclause.When a execute a SELECT on this temporary table sometimes the result isok, but sometimes is not ordered. I didn´t see anything like that. Anyclue?Is there any kind of limits with temporary tables ? Because the commandthat creates the temporary table is working and the rsults is alwaysordered. But when I create a table with it, sometimes the table is notordered.Paulo*** Sent via Developersdex http://www.developersdex.com ***Don't just participate in USENET...get rewarded for it!

View 2 Replies View Related

UNION: Select Order

Aug 31, 2007

i have 2 selects:select * from view_veiculos where nome_marc like '%fiat%' and ano='2001'union select * from view_veiculos where nome_marc like '%fiat%'when i execute it on sql server, i get the following results:id 1 _______ ano 2004id 2 _______ ano 2001the row with ano 2004 is before the row with ano 2001the problem is that id like it to be ordered following the select order, which means that 2001 should be displayed before 2004,like that:id 1 _______ ano 2001id 2 _______ ano 2004all the results from the first select from the query need to be placed before the results from the second query.how can i make it ?thanks for all

View 23 Replies View Related

How Do I Use Order By When I Use Select Distinct.

May 6, 2008

Hi
    I have a query which returns some rows.. what happens if i use a select distinct instead of a select.. this is my sproc
 DECLARE @Counter TABLE(
PlanId int,
FundId int,
ClientFundName varchar(110),
DisplayOrder int IDENTITY(1,1),
IsDefault bit,
IsPortfolioFundOnly bit
)
INSERT INTO @Counter
(
PlanId,
FundId,
ClientFundName,
IsDefault,
IsPortfolioFundOnly
)
SELECT
5923,
f.FundId,
d.FundName,
CASE WHEN d.FundDefault IS NULL THEN 0 ELSE 1 END,
CASE WHEN Lower(p.FundType) = 'modfundonly' THEN 1 ELSE 0 END
FROM
PlanDetail d
INNER JOIN Statements..Fund f
ON d.CUSIP = f.CUSIP
OR
d.Ticker = f.Ticker
OR
d.Ticker = f.ClientFundId
OR
d.CUSIP = f.ClientFundId
-- Do an internal join on the PlanDetail table to get the value of the FundType to derive whether
--fund can only be chosen as part of a portfolio.
LEFT JOIN PlanDetail p
ON d.FundName = p.FundName
AND
d.PortfolioName = p.PortfolioName
WHERE
d.PlanNumber IS NOT NULL
AND
p.PortFundPercent IS NULL
GROUP BY
f.FundId,
d.FundName,
d.FundDefault,
--d.PlanNumber,
--d.Cusip,
-- d.Ticker,
--d.RowNumber,
p.FundType

ORDER BY
Min(d.PlanNumber),
Min(d.RowNumber)


 any help will be appreciated.
Thanks
Karen

View 1 Replies View Related







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