首页 > 数据库技术 > 详细

sql生成数据库的序列号

时间:2014-04-04 14:41:34      阅读:515      评论:0      收藏:0      [点我收藏+]
bubuko.com,布布扣
-- =============================================
-- Author:        <Author,yaoyao,Name>
-- Create date: <Create Date,20130515,>
-- Description:    <Description,生成自定义ID,生成规则:1~5个字母前缀加5~10位数字>
-- =============================================
ALTER PROCEDURE [dbo].[proGetCustomID]
    @TableName VARCHAR(50),
    @FieldName VARCHAR(50),
    @BeginChar VARCHAR(5),
    @NumberLen INT=10--默认10
AS
BEGIN
    IF @NumberLen<5 or @NumberLen>10 set @NumberLen=10;
        
    DECLARE @CustomID VARCHAR(10),@MaxID VARCHAR(15),@strSql NVARCHAR(200);
    set @strSql=select @tempid = MAX(+@FieldName+) FROM +@TableName;
    exec sp_executesql @strSql,N@tempid VARCHAR(15) out,@MaxID out --参数赋值
    --print @MaxID;
    
    IF @MaxID IS NULL
    BEGIN
        SET @CustomID=0000000001;
    END
    ELSE
    BEGIN
        SET @MaxID = CONVERT(INT,REPLACE(@MaxID,@BeginChar,‘‘));--CONVERT(INT,SUBSTRING(@MaxID,LEN(@BeginChar)+1,10));
        SET @CustomID=@MaxID+1;
        --print @CustomID
        
        WHILE(LEN(@CustomID)<@NumberLen)
        BEGIN
            SET @CustomID=0+@CustomID
        END
    END
    
    SELECT @BeginChar+@CustomID;
END
bubuko.com,布布扣
bubuko.com,布布扣
/// <summary>
        /// 生成自定义ID
        /// </summary>
        /// <param name="tableName">表名</param>
        /// <param name="fieldName">生成id的字段</param>
        /// <param name="beginChar">1~5位字母</param>
        /// <returns></returns>
        public static string CreateID(string tableName, string fieldName, string beginChar)
        {
            SqlParameter[] parameters = {

                    new SqlParameter("@TableName", SqlDbType.VarChar, 20),
                    new SqlParameter("@FieldName", SqlDbType.VarChar, 20),
                    new SqlParameter("@BeginChar", SqlDbType.VarChar,10)};
            parameters[0].Value = tableName;
            parameters[1].Value = fieldName;
            parameters[2].Value = beginChar;
            return DbHelperSQL.GetSingleByPro("proGetCustomID", parameters).ToString();
        }
bubuko.com,布布扣

 

sql生成数据库的序列号,布布扣,bubuko.com

sql生成数据库的序列号

原文:http://www.cnblogs.com/mengxingxinqing/p/3644796.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!