2016-03-23 43 views
0

當我向表格中插入一行時,必須在c#中生成一個數字「Reference Number」。c#中的字符串+數字發生器#

該參考號碼應生成的數據被插入,並保存在表中的一列後:

我的表(dbo.Cha)的結構是:

ChaId (Primary Key) - 1 
CreatedDate (Date) - 23/03/2016 
ChaReferenceId (Varchar) - 

最終出了將"CHA0316001"

我要添加的「表名+月/年+ 00 +的PrimaryKey」 - CHA0316001 並保存在同一個表中的列「ChaReferenceId」列中的值 - dbo.cha

SQL服務器 - 程序:

CREATE PROCEDURE [dbo].[Cha_Insert] 
@ChaName varchar(50), 
@PortId int, 
@StateId int = NULL, 
@CountryId int, 
@Address varchar(50), 
@PhoneNumber int, 
@EmailId1 varchar(50), 
@CreatedDate date = NULL, 
@CreatedById int = NULL 
AS 

SET NOCOUNT ON 


INSERT INTO [dbo].[Cha] 
      ([ChaName] ,[PortId],[StateId],[CountryId],[Address],[PhoneNumber],[EmailId1],[CreatedDate],[CreatedById],[IsActive]) 
    VALUES(@ChaName, @PortId, @StateId, @CountryId,@Address,@PhoneNumber,@EmailId1,GETDATE(),@CreatedById,'true') 

GO 

的.cs代碼:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.UI; 
using System.Web.UI.WebControls; 
using System.Data.SqlClient; 
using System.Configuration; 
using System.Data; 

namespace User_Login_CS.Inventory 
{ 
    public partial class Cha : System.Web.UI.Page 
    { 

     private string message = string.Empty; 
     SqlConnection conn; 

     protected void Page_Load(object sender, EventArgs e) 
     { 
      if (!Page.IsPostBack) 
      { 
       PopulatePortName(); 
       PopulateStateName(); 
       PopulateCountryName(); 
      } 
     } 


     private Boolean InsertCha() 
     { 

      int intPortId = Convert.ToInt32(ddlPort.SelectedValue); 
      int intStateId = Convert.ToInt32(ddlState.SelectedValue); 
      int intCountryId = Convert.ToInt32(ddlCountry.SelectedValue); 

      Boolean blnSuccess = true; 

      try 
      { 
       conn = GetConnection(); 

       SqlCommand cmd = new SqlCommand("Cha_Insert", conn); 
       cmd.CommandType = CommandType.StoredProcedure; 
       cmd.Parameters.Add("@ChaName", SqlDbType.VarChar).Value = txtChaName.Text; 
       cmd.Parameters.Add("@PortId", SqlDbType.Int).Value = ddlPort.SelectedValue; 
       cmd.Parameters.Add("@StateId", SqlDbType.Int).Value = ddlState.SelectedValue; 
       cmd.Parameters.Add("@CountryId", SqlDbType.Int).Value = ddlCountry.SelectedValue; 
       cmd.Parameters.Add("@Address", SqlDbType.VarChar).Value = txtAddress.Text; 
       cmd.Parameters.Add("@PhoneNumber", SqlDbType.Int).Value = txtPhone.Text; 
       cmd.Parameters.Add("@EmailId1", SqlDbType.VarChar).Value = txtEmail1.Text; 
       cmd.Parameters.Add("@CreatedById", SqlDbType.Int).Value = Convert.ToInt32(Session["userid"]); 


       cmd.ExecuteNonQuery(); 
      } 
      catch (Exception ex) 
      { 
       blnSuccess = false; 
       lblmessage.Visible = true; 
       lblmessage.Text = "Error Occured: " + ex.Message; 
      } 

      return blnSuccess; 
     } 



     private void PopulatePortName() 
     { 
      conn = GetConnection(); 

      SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM [Port]", conn); 

      DataSet dsPort = new DataSet(); 

      da.Fill(dsPort, "dsPort"); 

      ddlPort.DataSource = dsPort.Tables["dsPort"]; 
      ddlPort.DataTextField = "PortCode"; 
      ddlPort.DataValueField = "PortId"; 
      ddlPort.DataBind(); 
      conn.Close(); 
     } 


     private void PopulateStateName() 
     { 
      conn = GetConnection(); 

      SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM [PortState]", conn); 

      DataSet dsState = new DataSet(); 

      da.Fill(dsState, "dsState"); 

      ddlState.DataSource = dsState.Tables["dsState"]; 
      ddlState.DataTextField = "StateName"; 
      ddlState.DataValueField = "StateId"; 
      ddlState.DataBind(); 
      conn.Close(); 

     } 
     private void PopulateCountryName() 
     { 
      conn = GetConnection(); 

      SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM [PortCountry]", conn); 

      DataSet dsCountry = new DataSet(); 

      da.Fill(dsCountry, "dsCountry"); 

      ddlCountry.DataSource = dsCountry.Tables["dsCountry"]; 
      ddlCountry.DataTextField = "CountryName"; 
      ddlCountry.DataValueField = "CountryId"; 
      ddlCountry.DataBind(); 
      conn.Close(); 
     } 


     private Boolean CheckEmailId() 
     { 
      conn = GetConnection(); 
      Boolean blnExists = false; 

      SqlDataAdapter ei = new SqlDataAdapter("SELECT * FROM Cha where EmailId1='" + txtEmail1.Text + "'", conn); 
      DataSet dsEmailId = new DataSet(); 
      ei.Fill(dsEmailId); 
      if (dsEmailId.Tables[0].Rows.Count > 0) 
      { 
       blnExists = true; 
       //conn.Close(); 
      } 
      else 
      { 
       blnExists = false; 
      } 
      return blnExists; 
     } 



     private SqlConnection GetConnection() 
     { 
      conn = new SqlConnection(); 

      conn.ConnectionString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString; 
      conn.Open(); 
      return conn; 
     } 



     protected void btnInsertCha_Click(object sender, EventArgs e) 
     { 

      //int intPortId = Convert.ToInt32(ddlPort.SelectedValue); 
      //int intStateId = Convert.ToInt32(ddlState.SelectedValue); 
      //int intCountryId = Convert.ToInt32(ddlCountry.SelectedValue); 


      Boolean blnExists = false; 
      blnExists = CheckEmailId(); 

      Boolean blnSuccess = true; 

      if (!blnExists) 
      { 
       blnSuccess = InsertCha(); 
       if (blnSuccess) 
       { 
        lblmessage.Visible = true; 
        lblmessage.Text = "User Successfully Cha Agent Registered!!!"; 
       } 
      } 
      else 
      { 
       lblmessage.Visible = true; 
       lblmessage.Text = "Email Id Already Exists!!!"; 
      } 
     } 


    } 
} 

表結構

/****** Object: Table [dbo].[Cha] Script Date: 03/23/2016 12:26:47 ******/ 
SET ANSI_NULLS ON 
GO 

SET QUOTED_IDENTIFIER ON 
GO 

SET ANSI_PADDING ON 
GO 

CREATE TABLE [dbo].[Cha](
    [ChaId] [int] IDENTITY(1,1) NOT NULL, 
    [ChaName] [varchar](50) NOT NULL, 
    [PortId] [int] NOT NULL, 
    [StateId] [int] NULL, 
    [CountryId] [int] NOT NULL, 
    [Address] [varchar](50) NOT NULL, 
    [PhoneNumber] [int] NOT NULL, 
    [EmailId1] [varchar](50) NOT NULL, 
    [CreatedDate] [date] NOT NULL, 
    [CreatedById] [int] NULL, 
    [ModifiedDate] [date] NULL, 
    [ModifiedById] [int] NULL, 
    [IsActive] [bit] NOT NULL, 
    [ChaReferenceId] [varchar](50) NULL, 
CONSTRAINT [PK_Cha_1] PRIMARY KEY CLUSTERED 
(
    [ChaId] ASC 
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] 
) ON [PRIMARY] 

GO 

SET ANSI_PADDING OFF 
GO 
+0

如果我理解你的數據類型是正確的 - 那麼這可以直接在數據庫中進行(觸發爲例),或者你可以使用輸出到獲取變量值返回到您的代碼。 –

+0

你的問題是什麼? –

+0

標記使用的dbms。該代碼根本不像ANSI SQL。 – jarlh

回答

3

您可以通過使用Computed列在創建表做到這一點

CREATE TABLE [dbo].[Cha](
[ChaId] [int] IDENTITY(1,1) NOT NULL, 
[ChaName] [varchar](50) NOT NULL, 
[PortId] [int] NOT NULL, 
[StateId] [int] NULL, 
[CountryId] [int] NOT NULL, 
[Address] [varchar](50) NOT NULL, 
[PhoneNumber] [int] NOT NULL, 
[EmailId1] [varchar](50) NOT NULL, 
[CreatedDate] [date] NOT NULL, 
[CreatedById] [int] NULL, 
[ModifiedDate] [date] NULL, 
[ModifiedById] [int] NULL, 
[IsActive] [bit] NOT NULL, 
[ChaReferenceId] AS ('YourTableName' + REPLACE(RIGHT(CONVERT(char(8), CreatedDate, 5), 5), '-', '') + RIGHT('00'+ CAST(ChaId as varchar), 3)), 
CONSTRAINT [PK_Cha_1] PRIMARY KEY CLUSTERED 
(
    [ChaId] ASC 
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] 
) ON [PRIMARY] 

計算列

[ChaReferenceId] AS Convert(VARCHAR(50),('YourTableName' + REPLACE(RIGHT(CONVERT(char(8), CreatedDate, 5), 5), '-', '') + RIGHT('00'+ CAST(ChaId as varchar), 3))) 
+0

可以請你把它合併到上面的那個 –

+1

你的答案是我會走的路,但我認爲你的As子句是錯誤的。如果月份是三月,將'MONTH'鑄造到varchar將返回'3';如果主鍵已經有一個數字以上,則連接'00'到主鍵將返回一個長度超過3位的字符串。我會這樣做:''YourTableName'+ REPLACE(RIGHT(CONVERT(char(8),CreatedDate,5),5),' - ','')+ RIGHT('00'+ CAST(ChaId as varchar ),3)' –

+0

@ZoharPeled是的,好抓住:) –