1:存储过程实现自增长的功能是面试常考点:我写一个实例,实现主键编号为4位的自增长的varchar50的增长,实际面试的时候要用bigint类型,而且那些相对来说比较简单:
表结构如下:
create table classMgr(
id varchar(50) primary key not null,
Name Nvarchar(50))
存储过程如下:
create proc query_id(
@maxId varchar(50) output) as begin declare @currentId varchar(50) select top 1 @currentId=dbo.classMgr.id from dbo.classMgr order by id desc select @maxId=RIGHT('0000'+LTRIM(cast(isnull(@currentId,'0') as integer)+1),4) end执行存储过程:
declare @maxId bigint; exec query_id @maxId output print @maxId得出的结构:
已达到预期要的结果。
asp.net调用存储过程:
string connectiongString = "server=.;database=test;uid=sa;pwd=2009@ABCDEF";
SqlConnection conn = new SqlConnection(connectiongString); try { conn.Open(); SqlCommand cmd = new SqlCommand(); cmd.CommandType = CommandType.StoredProcedure; cmd.Connection = conn; cmd.CommandText = "query_id"; SqlParameter par = new SqlParameter("@maxId", SqlDbType.VarChar,50); par.Direction = ParameterDirection.Output; cmd.Parameters.Add(par); cmd.ExecuteNonQuery(); this.lblMyId.Text = par.Value.ToString(); } catch (Exception err) { conn.Close(); throw new Exception(err.Message + err.StackTrace); } finally { conn.Dispose(); }