您可以使用类似于以下的 SQL 代码在数据库上创建序列对象:
CREATE SEQUENCE Test.CountBy1TestSequence
START WITH 1
INCREMENT BY 1 ;
GO
然后可以使用 SQL 调用:
SELECT NEXT VALUE FOR Test.CountBy1TestSequence;
或通过 dapper 调用:
using (var conn = new SqlConnection(ConnectionString))
{
String sql = @"SELECT NEXT VALUE FOR Test.CountBy1TestSequence";
var result = conn.ExecuteScalar<Int>(sql);
// Do whatever with the result
}
使用序列值,您可以使用 dapper 将其传递到数据库上的存储过程,代码类似于以下内容:
var p = new DynamicParameters();
p.Add("@inputInvoiceNumber", $"INV{DateTime.Now.Year}-{DateTime.Now.Month}-{result}, DbType.String, ParameterDirection.Input);
p.Add("@retVal", dbType: DbType.Int32, direction: ParameterDirection.ReturnValue); // If there is any return
cnn.Execute("spTestProc", p, commandType: CommandType.StoredProcedure);
其中@inputInvoiceNumber 和@retVal 是存储过程中的参数。