【问题标题】:SQL Server: Auto increment decimal columnSQL Server:自动递增小数列
【发布时间】:2017-03-24 08:04:53
【问题描述】:

我需要在 SQL Server 2014 中自动增加一个小数列。

【问题讨论】:

  • 首先...为什么?二、有多少DP?请提供样本数据。
  • 试过了,得到这个错误信息:Identity column 'D' must be of data type int, bigint, smallint, tinyint, or decimal or numeric with a scale of 0, and constrained to be nonnullable.
  • @JohnHC 我必须提供它自动生成的版本号。示例:1.0、2.0、. . .
  • @ZoharPeled 我也遇到了同样的错误。我想我们还没有这样的选择。

标签: sql sql-server auto-increment


【解决方案1】:

我的实际要求是为我的存储过程的每次调用生成一个版本号。我已经实现了如下。

在外部创建和更新表

create table version(no decimal(2,2)) insert into version(1.0)

下面是我的存储过程的小摘录

Update version set no=(select max(no) from version)+1

select no.version,t.* from table t left join version

【讨论】:

    【解决方案2】:

    您应该告诉我们您想要实现什么,但是模拟自动递增十进制列的一种方法是将其定义为计算并连接到自动递增的普通(整数)列。例如:

    定义:

    create table AutoincrementDecimalTest
    (
        Id INT NOT NULL IDENTITY(1, 1),
        SomeText NVARCHAR(200) NOT NULL,
        -- you may declare it as persisted, if the extra space is not problem
        AutoincrementDec AS CAST(Id * 0.2 AS NUMERIC(18, 2))
    )
    

    当然,正如here 所指出的,您的表达方式存在一些限制。

    测试:

    insert into AutoincrementDecimalTest (SomeText) VALUES ('test1'), ('test2')
    GO
    
    select * from AutoincrementDecimalTest
    GO
    

    【讨论】:

    • 谢谢。我的实际要求是为我的逻辑的每次迭代生成一个版本号。我确实做到了这一点,如下所示。使用 1.0 Declare @var Decimal(5,2) Set @var=1.0 启动一个十进制变量,然后在我的逻辑循环中将其设置为 @Var+1。 ` 设置@var= @var+1 打印@var `
    • 您的解决方案可能有效,但您应该从基于集合的角度考虑 - 自动生成一次多次插入可能比 while 循环中的单次插入要快得多。
    【解决方案3】:

    decimal 中的声明,但您只能选择整数格式。

    CREATE TABLE #Record(id decimal(18,0) identity primary key , name VARCHAR(100))
    INSERT INTO #Record( name )SELECT 'name1' UNION ALL SELECT 'name2' SELECT * FROM #Record
    

    【讨论】:

      猜你喜欢
      • 2019-02-14
      • 2012-01-13
      • 2014-04-15
      • 1970-01-01
      • 1970-01-01
      • 2011-01-31
      • 2021-01-07
      • 1970-01-01
      • 2011-04-06
      相关资源
      最近更新 更多