在 C# 中生成序列号

编程入门 行业动态 更新时间:2024-10-19 00:29:50
本文介绍了在 C# 中生成序列号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在使用 C# 处理 ASP.Net 我想生成一个应该是这样的序列 ID:

I am working on ASP.Net using C# I want to generate a sequence id that should be like this:

ELG0001 , ELG0002, ...

ELG 是 PREFIX 和 0001 应该是顺序

ELG is the PREFIX and 0001 should be in sequence

我使用的是 sql server 2005

I am using sql server 2005

此 ID 将生成并添加到我的数据库中.我该怎么做?

This ID will be generated and added to my database. How can I do this?

你能帮我写代码吗?

推荐答案

使用这段代码,我们可以很简单

using this code we can do it simply

public string CJ() { string Id = GenerateId("cust", "cust_id", 6, "ELG", true); return Id; } public string GenerateId(string TableName, string ColumnName, int ColumnLength, string Prefix, bool Padding) { string Query, con, Id; con = "Data Source=CJ\\SQLEXPRESS;Initial Catalog=seq;Persist Security Info=True;User ID=sa;Password=123"; SqlConnection cn = new SqlConnection(con); int preLength,padLength; preLength = Convert.ToInt32(Prefix.Length); padLength = ColumnLength - preLength; if (Padding == true ) { Query = "SELECT '" + Prefix + "' + REPLACE(STR(MAX(CAST(SUBSTRING(" + ColumnName + "," + Convert.ToString(preLength + 1) + "," + padLength + ") AS INTEGER))+1," + padLength + "),' ',0) FROM " + TableName; } else { Query = "SELECT '" + Prefix + "' + CAST(MAX(CAST(SUBSTRING(" + ColumnName + "," + Convert.ToString(preLength + 1) + "," + padLength + ") AS INTEGER))+1 AS VARCHAR) FROM " + TableName; } SqlCommand com = new SqlCommand(Query, cn); cn.Open(); if (com.ExecuteScalar().ToString() == "") { Id = Prefix; if (Padding == true) { for (int i = 1; i padLength - 1; i++) { Id += "0"; } } Id += "1"; } else { Id = Convert.ToString(com.ExecuteScalar()); } cn.Close(); return Id; }

thanxx 寻求帮助只需添加方法 CJ()正如我在这里所做的那样

thanxx for the help just add the method CJ() as i have done here

protected void Button1_Click(object sender, EventArgs e) { string con; con = "Data Source=CJ\\SQLEXPRESS;Initial Catalog=seq;Persist Security Info=True;User ID=sa;Password=123"; using (SqlConnection cn = new SqlConnection(con)) { cn.Open(); using(SqlTransaction trans = cn.BeginTransaction()) using (SqlCommand cmd = cn.CreateCommand()) { cmd.Transaction = trans; cmd.CommandText = "INSERT INTO cust([cust_id],[cust_name],[cust_add]) VALUES(@cust_id,@cust_name,@cust_add)"; cmd.Parameters.Add("@cust_id",CJ()); cmd.Parameters.Add("@cust_name",TextBox1.Text); cmd.Parameters.Add("@cust_add",TextBox2.Text); cmd.ExecuteNonQuery(); trans.COmmit(); } cn.Close(); Response.Write("alert('DATA SAVED')"); TextBox1.Text = ""; TextBox2.Text = ""; } }

更多推荐

在 C# 中生成序列号

本文发布于:2023-10-26 23:48:19,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1531699.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:序列号

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!