在ASP程序中生成序号的方法有多种,以下是几种常见的方法:
方法一:使用数据库自增字段
创建表结构
```sql
CREATE TABLE xtab (
seq_id int PRIMARY KEY,
create_time datetime
);
```
存储过程或SQL语句
```sql
BEGIN TRANSACTION;
DECLARE @max_seq int;
SELECT @max_seq = MAX(seq_id) FROM xtab WITH (TABLOCKX);
SET @max_seq = ISNULL(@max_seq, 0);
SET @max_seq = @max_seq + 1;
INSERT INTO xtab VALUES (@max_seq, GETDATE());
COMMIT;
```
ASP代码示例
```asp
<%
Dim conn, sql, rs
Set conn = Server.CreateObject("ADODB.Connection")
conn.Open "Provider=SQLOLEDB;Data Source=(local);Initial Catalog=YourDatabase"
sql = "BEGIN TRANSACTION; DECLARE @max_seq int; SELECT @max_seq = MAX(seq_id) FROM xtab WITH (TABLOCKX); SET @max_seq = ISNULL(@max_seq, 0); SET @max_seq = @max_seq + 1; INSERT INTO xtab VALUES (@max_seq, GETDATE()); COMMIT;"
conn.Execute sql
Dim rs, seq_id
Set rs = conn.Execute("SELECT @@IDENTITY AS seq_id")
seq_id = rs("seq_id")
Response.Write "新序号是: " & seq_id
%>
```
方法二:使用数据库种子表
创建种子表
```sql
CREATE TABLE SEED (
BM varchar(20) NOT NULL,
BH varchar(12) NOT NULL,
constraint PK_SEED PRIMARY KEY(BM)
);
```
插入表名到种子表
```sql
INSERT INTO SEED (BM, BH) VALUES ('tablename', '200211070000');
```
存储过程生成新编号
```sql
CREATE PROCEDURE proc_getbh @BM varchar(20) AS
BEGIN
DECLARE @BH char(12)
DECLARE @TODAY char(8)
SELECT @BH = BH FROM SEED WHERE BM = @BM
SET @TODAY = FORMAT(GETDATE(), 'yyyyMMdd')
IF @BH IS NULL
BEGIN
INSERT INTO SEED (BM, BH) VALUES (@BM, @TODAY)
SET @BH = @TODAY
END
SELECT @BH AS NewNumber
END
```
ASP代码示例
```asp
<%
Dim conn, sql, rs
Set conn = Server.CreateObject("ADODB.Connection")
conn.Open "Provider=SQLOLEDB;Data Source=(local);Initial Catalog=YourDatabase"
Dim tableName
tableName = "YourTableName"
sql = "EXEC proc_getbh '" & tableName & "'"
conn.Execute sql
Dim rs, newNumber
Set rs = conn.Execute("SELECT NewNumber FROM proc_getbh('" & tableName & "')")
newNumber = rs("NewNumber")
Response.Write "新序号是: " & newNumber
%>
```
方法三:使用自增变量和表锁定
创建表结构
```sql
CREATE TABLE xtab (
seq_id int PRIMARY KEY,
create_time datetime
);
```
存储过程或SQL语句
```sql
BEGIN TRANSACTION;
DECLARE @max_seq int;
SELECT @max_seq = MAX(seq_id) FROM xtab WITH (TABLOCKX);
SET @max_seq = ISNULL(@max_seq, 0);
SET @max_seq = @max_seq + 1;
INSERT INTO xtab VALUES (@max_seq, GETDATE());
COMMIT;
```