自动递增患者ID

时间:2014-11-24 13:44:39

标签: c# sql sql-server

我一直在为医院管理创建C#项目,其中我考虑了一些基本文本值,例如Patient name,PatientID,Gender等,以及一些用于保存功能的按钮等。我使用SqlClient来存储值。我只是想知道如何设置PatientID,以便每次输入新记录时PatientID自动增加1。必须为用户禁用PatientID文本,并且需要为每个新记录自动递增。

有人可以帮忙吗? 在此先感谢:)

4 个答案:

答案 0 :(得分:2)

像这样创建表:

CREATE TABLE [dbo].[Patient](
    [PatientID] [int] IDENTITY(1,1) NOT NULL,
    [PatientName] [nvarchar](max) NOT NULL,
    [Gender] [bit] NULL,
 CONSTRAINT [PK_Patient] PRIMARY KEY CLUSTERED 
(
    [PatientID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

答案 1 :(得分:1)

您可以在创建表set Identity to YES and increament it by 1

时执行此@ table级别

这里是您的参考enter image description here

答案 2 :(得分:0)

如果您使用的是DataTable,那么您可以设置AutoIncrementColumn = True,这将在每个条目上递增。

    Dim column As DataColumn = New DataColumn
    column.DataType = System.Type.GetType("System.Int32")
    With column
        .AutoIncrement = True
        .AutoIncrementSeed = 1000
        .AutoIncrementStep = 10
    End With 

    ' Add the column to a new DataTable. 
    Dim table As DataTable
    table = New DataTable
    table.Columns.Add(column)

DataColumn.AutoIncrement

答案 3 :(得分:-2)

我在我的一个项目中以编程方式创建了表格

    public void CreateTables()
    {
        SqlConnection conn1 = new SqlConnection();

        try
        {

            // Drop and Create a new Patient Table
            string queryDrop = "IF OBJECT_ID('Patient', 'U') IS NOT NULL DROP TABLE Patient";


            conn1.ConnectionString = GetConnectionString();
            conn1.Open();

            SqlCommand cmdDrp = new SqlCommand(queryDrop, conn1);
            cmdDrp.ExecuteNonQuery();


            string query = "CREATE TABLE Patient(" +
                      "PatientId uniqueidentifier DEFAULT NEWSEQUENTIALID()," +
                      "PatientName varchar(50) NOT NULL," +
                      "Gender varchar(50) NOT NULL," +
                   ")";
            SqlCommand cmd1 = new SqlCommand(query, conn1);

            cmd1.ExecuteNonQuery()
        }
        catch (Exception)
        {

            throw;
        }
        finally
        {
            conn1.Close();//close the connection
        }
 }

    public string GetConnectionString()
    {
        string folderpath = Environment.GetFolderPath
        (Environment.SpecialFolder.Personal);      

        string connStr = "Data Source=.\\SQLEXPRESS;AttachDbFilename=" + folderpath
        + "\\FolderName\\Hospitaldata.mdf;Integrated Security=True;" +
        "Connect Timeout=30;User Instance=True";

        return connStr;

    }