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


ADVERTISEMENT

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

Return Random Rows

May 6, 2006

Are there any way to execute a procedure and return N random rows?

View 10 Replies View Related

Random Rows In Respect To Their Priorities

Sep 28, 2007

I need to build an SQL query, which generates the random rows priority wise.
I found this on following article.
http://articlesdotnet.blogspot.com/2007/09/random-rows-in-respect-to-their.html
Can anyone test it?
In addition, tell me.
Is it good or have a bug?
If anyone have the better query then please tell me.

View 5 Replies View Related

SQL Server Random Rows Returned

Sep 23, 2004

As a part of my unpaid internship, I am creating a ASP.NET interface for a MS SQL Server 2000. The table I am having problems with has over 750,000 rows by 26 columns. There isn't a primary key. It stores a transaction dump from another primitive Database server.

Problem:

When perform a query I get one set of results. I run the same query again after a short wait and the rows returned are in a different order. The majority of the rows returned are the same ones returned in the previous query. Only, some rows may be missing and the order may change.

I really wasn't surprised by some duplicate rows. I am confused why they are showing up in a different order and the above mentioned inconsistancy in results.

I thought I was having problems with my Repeater Control; however, SQL Query Analyzer returns the same results.


Question:

What is causing the problem?

View 3 Replies View Related

Distinct Random Rows Using NewID()

May 26, 2008

I have 2 tables, Artists and Artworks.
I have a query:

SELECT TOP (4) dbo.Artists.ArtistID, dbo.Artists.FirstName + ' ' + dbo.Artists.LastName AS FullName, dbo.Artworks.ArtworkName, dbo.Artworks.Image
FROM dbo.Artists INNER JOIN
dbo.Artworks ON dbo.Artists.ArtistID = dbo.Artworks.ArtistID
ORDER BY NEWID()

This query returns random images, but the artists are sometimes repeated.
I would like to have DISTINCT Random Artists returned, each with a random image. I tried various subqueries, but I just get error messages.
Any help would be appreciated.
Thnks,

Paolo

View 8 Replies View Related

Flat File With Random Bad Rows.

Aug 13, 2007

I have a text file that come from our client that is Column deliminated by ~ and row deliminated by {CR}{LF}.
There is a comment field that appearently is not cleaned up and has {CR}{LF} within the comment field.

I am new to SSIS and I'm wondering if there is a way to detect and correct the bad rows?

example file formet:

ORDERID~DATE~Comment~Address
1~2/3/2007~Some Comment~1234 oak st
2~2/3/2007~Some messed
up comment~345 oak st.
3~2/3/2007~Another comment~3214 asdf blvd.


Thank you.

View 8 Replies View Related

Transact SQL :: Getting Random Rows From Table / Two From Each Group

Sep 2, 2015

I am using Sql Server 2008 R2.I have a existing query that basically says

Select Top 50 Subscriber_ID,  Member_Name, Group_ID
from my_table
order by rand(checksum(newid()))

However the client now wants to have at least two from each group_id. There are 17 different groups.  When I run this as is I get about six of the 17 groups in the results.  How can I change this to get at least two results from each group_id?

View 6 Replies View Related

Select Rows From Another Server's Database

Jun 2, 2003

Hi,

I need to import data from another server on recurring basis. Before inserting the data, I need to perform some checking e.g. check the last update date and time.

I am thinking of scheduling SQL job that run SQL Query. The SQL query will make use of cursor to check each row, to decide what to do with the imported data

Is it the right way to import the data? However I did not know how to select data from another server using T-SQL. Can help? I am using SQL 2000

Thanks in advance

Regards,
Christine

View 8 Replies View Related

Select No. Of Rows From The Current Database

Jul 19, 2006

Hello,I want to select the names and number of rows of all tables in thecurrent database, whose name starts with 'sys'my query is:select o.[name], sum(i.[rows]) as numbersfrom sysobjects oinner join sysindexes ion (o.[id] = i.[id])where o.[name] like 'sys%'and i.indid=1group by o.[name]the result of the query is (depending of the database) :name numberssysaltfiles 14syscharsets 114syscolumns 4934syscomments 2035sysconfigures 38sysdatabases 7sysdepends 5524sysdevices 6sysfilegroups 1sysfulltextcatalogs 0sysfulltextnotify 0sysindexes 98syslanguages 33sysmessages 3795sysobjects 1285syspermissions 806sysproperties 0sysreferences 0sysservers 1systypes 26sysusers 14sysxlogins 3But when I count the number of rows of "sysobjects", I getnumbers=1298, which is different from the result displayed above andsame goes for "syscolumns".I also tried "dbcc updateusage [0]" to update the SQL Server but Ididnt help me.Can anyone please advice me on this behaviour?

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

Select Rows From Database Where Fields Are Null

Dec 30, 2006

Hi, how do i do a select statement with asp.net to return a record if a field is null.  I have the following code:
SqlCommand cmd = new SqlCommand("SELECT * FROM Categories WHERE ParentId = @ParentId", cn);.Parameters.Add("@ParentId", SqlDbType.Int).Value = parentId != null ? (object) parentId : DBNull.Value;cn.Open();
The variable parentId is a nullable int.  However when i pass in a null value it doesn't return anything even though there are records in the database that have a null value for the ParentId field.
Appreciate if someone could tell me what i am doing wrong.  Thanks

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

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

DataSet Rows Being Deleted, But After The Update , The Sql Database Is Not Updated. The Delete Rows Still In The Database.

Jun 4, 2007

 Stepping thru the code with the debugger shows the dataset rows being deleted.
 
After executing the code, and getting to the page presentation. Then I stop the debug and start the
page creation process again ( Page_Load ).    The database still has the original deleted dataset rows.
Adding rows works, then updating works fine, but deleting rows, does not seem to work.
 
The dataset is configured to send the DataSet updates to the database. Use the standard wizard to create the dataSet.
 
 
cDependChildTA.Fill(cDependChildDs._ClientDependentChild, UserId);        rowCountDb = cDependChildDs._ClientDependentChild.Count;               for (row = 0; row < rowCountDb; row++)        {           dr_dependentChild = cDependChildDs._ClientDependentChild.Rows[0];           dr_dependentChild.Delete();                      //cDependChildDs._ClientDependentChild.Rows.RemoveAt(0);           //cDependChildDs._ClientDependentChild.Rows.Remove(0);            /* update the Client Process Table Adapter*/          // cDependChildTA.Update(cDependChildDs._ClientDependentChild);      //     cDependChildTA.Update(cDependChildDs._ClientDependentChild);        }
        /* zero rows in the DataSet at this point */        /* update the Child  Table Adapter */       cDependChildTA.Update(cDependChildDs._ClientDependentChild);

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

Select Distinct Rows From Duplicate Rows....

Nov 28, 2007

Dear Gurus,I have table with following entriesTable name = CustomerName Weight------------ -----------Sanjeev 85Sanjeev 75Rajeev 80Rajeev 45Sandy 35Sandy 30Harry 15Harry 45I need a output as followName Weight------------ -----------Sanjeev 85Rajeev 80Sandy 30Harry 45ORName Weight------------ -----------Sanjeev 75Rajeev 45Sandy 35Harry 15i.e. only distinct Name should display with only one value of Weight.I tried with 'group by' on Name column but it shows me all rows.Could anyone help me for above.Thanking in Advance.RegardsSanjeevJoin Bytes!

View 4 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 * Not Returning Any Rows, But SELECT COL_NAME Does!

Jul 20, 2005

I have a table which is returning inconsistent results when I queryit!In query analyzer:If I do "SELECT * FROM TABLE_NAME" I get no rows returned.If I do "SELECT COL1, COL2 FROM TABLE_NAME" I get 4 rows returned.In Enterprise manager:If I do "return all rows" I get 4 rows returned, and the SQL is listedas being "SELECT * FROM dbo.TABLE_NAME".I've tried adding the "dbo." before my table name in QA, but it seemsto make no difference.I'm using SQL Server 2000, which is apparently 8.00534.Can anyone help me, or give me ideas about what to check?Thanks,Rowland.

View 9 Replies View Related

Select All Rows Except Some Rows

Feb 3, 2006

Hi all,

Is it possible to say something like

INSERT INTO Book
Book.* EXCEPT (a,c,d)

Something like WITHOUT
DESELECT
EXCLUDING
LESS

Thanks

View 4 Replies View Related

When I Use SSIS For Extract From OLAP Database, Then The Error Random Occurred,Error Code = 0x80040E05

May 10, 2007



I have tired for this!

When I use SSIS for extract data from ssas, that means,I use mdx query.

then random error occured.



Hope some one can understand my poor English....



And the Error Info show below.






Code Snippet

Error: 0xC0202009 at Data Flow Task - For Individual User Tech Points, OLE DB Source 1 1 [31]: SSIS Error Code DTS_E_OLEDBERROR. An OLE DB error has occurred. Error code: 0x80040E05.
An OLE DB record is available. Source: "Microsoft OLE DB Provider for Analysis Services 2005" Hresult: 0x00000001 Description: "Error Code = 0x80040E05, External Code = 0x00000000:.".
Error: 0xC004701A at Data Flow Task - For Individual User Tech Points, DTS.Pipeline: component "OLE DB Source 1 1" (31) failed the pre-execute phase and returned error code 0xC0202009.

View 6 Replies View Related







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