如何从数据表中获取特定行的记录?

时间:2013-12-14 10:04:05

标签: c# sql

我正在使用C#和SQL服务器。我使用了顶级查询,但它只给出了数据表中的最高结果。通过在文本框中输入此值,我想要20-40或30-100行的结果。

CREATE TABLE [dbo].[newpatient] (
[id]          INT           IDENTITY (1, 1) NOT NULL,
[serialno]    VARCHAR (MAX) NULL,
[patientname] VARCHAR (100) CONSTRAINT [DF__newpatien__patie__1273C1CD] DEFAULT ('') NULL,
[age]         INT           CONSTRAINT [DF__newpatient__age__1367E606] DEFAULT ((0)) NULL,
[address]     VARCHAR (100) CONSTRAINT [DF__newpatien__addre__145C0A3F] DEFAULT ('') NULL,
[symptoms]    VARCHAR (MAX) CONSTRAINT [DF__newpatien__sympt__15502E78] DEFAULT ('') NULL,
[medicine]    VARCHAR (MAX) CONSTRAINT [DF__newpatien__medic__164452B1] DEFAULT ('') NULL,
[bookingdate] DATETIME      NULL,
[alloteddate] DATETIME      NULL,
[village]     VARCHAR (MAX) CONSTRAINT [DF__newpatien__villa__173876EA] DEFAULT ('') NULL,
[thana]       VARCHAR (MAX) CONSTRAINT [DF__newpatien__thana__182C9B23] DEFAULT ('') NULL,
[district]    VARCHAR (MAX) CONSTRAINT [DF__newpatien__distr__1920BF5C] DEFAULT ('') NULL,
[state]       VARCHAR (MAX) CONSTRAINT [DF__newpatien__state__1A14E395] DEFAULT ('') NULL,
[isvalid]     BIT           CONSTRAINT [DF__newpatien__isval__1B0907CE] DEFAULT ('') NULL,
CONSTRAINT [pk_id_newpatient] PRIMARY KEY CLUSTERED ([id] ASC)

);

try
   {
     SuperClass sc = new SuperClass();
     Cursor = Cursors.WaitCursor;
     timer1.Enabled = true;
     rptPatients rpt = new rptPatients();// created report
     SqlCommand MyCommand = new SqlCommand();
     SqlDataAdapter myDA = new SqlDataAdapter();
     DB_DOCTORDataSet myDS = new DB_DOCTORDataSet();//created dataset
     SqlConnection con = new SqlConnection("Data Source=(local);Initial Catalog=DB_DOCTOR;Integrated Security=True;Asynchronous Processing=True");
     MyCommand.Connection = con;
     MyCommand.CommandText = "select top '" + textBox1.Text + "' * from NewPatient";
     MyCommand.CommandType = CommandType.Text;
     myDA.SelectCommand = MyCommand;
     myDA.Fill(myDS, "NewPatient");
     rpt.SetDataSource(myDS);
     crystalReportViewer1.ReportSource = rpt;
   }
catch (Exception ex)
   {
     MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
   }

2 个答案:

答案 0 :(得分:1)

你不能使用TOP子句选择一个间隔,例如20到40.最简单的方法是选择TOP 40,然后丢弃客户端上的前19行。

稍微简单一点就是将查询更改为

WITH T AS
(
    SELECT TOP 40 NP.*, row_number() OVER (ORDER BY id) AS RN from NewPatient NP Order by xx
)
SELECT * from T where RN>=20

答案 1 :(得分:0)

如果数据库中的数据按ID排序,为什么不使用:

MyCommand.CommandText = "select * from NewPatient where id between  " + textBox1.Text + " and " + textBox2.Text + " from NewPatient";

textBox1和textBox2包含您想要获取的记录范围。