SQL到数字桶

时间:2018-07-06 10:14:54

标签: sql sql-server-2012

所以我试图把工作日浪费在水桶里,但我被卡住了:

IF OBJECT_ID('mattexcel2') IS NOT NULL DROP TABLE mattexcel2 PRINT ' DROP TEMP TABLE'
SELECT * INTO mattexcel2 FROM SA_MASTER_BASE PRINT ' INSERT INTO TEMP TABLE'
GO
ALTER TABLE mattexcel2 ADD [Bucket] NVARCHAR(255) PRINT 'Bucket'
GO
UPDATE mattexcel2 SET [Bucket] = '0-3 Days' where [Business days in current Status] <= 3
GO

当我在SQL中运行此命令时,我得到:

  

将nvarchar值'1.91'转换为数据时转换失败   输入int。

因此,我希望1.9属于“ 0-3天”,属于“ Bucket”列。

1 个答案:

答案 0 :(得分:1)

如评论中所述,问题是:

[Business days in current Status] <= 3

由于[Business days in current Status]是字符串,因此需要将其转换为数字以进行比较。 SQL Server选择一个整数。您可以使用小数点位数来解决此问题:

UPDATE mattexcel2
    SET [Bucket] = '0-3 Days' 
    WHERE try_convert(decimal(38, 4), [Business days in current Status]) <= 3.0;

但是,我建议您使用计算列:

alter table mattexcel2
    add bd_bucket as (case when try_convert(decimal(38, 4), [Business days in current Status]) <= 3.0
                           then '0-3 Days'
                      end);

计算列将始终具有正确的值,而不会被更新。