【问题标题】:passing a variable as a parameter to varchar() as in cast(column1 as varchar(@variable))将变量作为参数传递给 varchar(),如 cast(column1 as varchar(@variable))
【发布时间】:2019-11-15 19:30:12
【问题描述】:

使用 SQL Server 2014。作为挑战,有人要求我在 select 语句中将 113.05 作为 0.05 返回。

我提出以下内容:

declare @temp1 table (value1 numeric(5,2))
insert into @temp1 (value1)
values
(113.05);

select value1, cast('.' + right(cast(value1 as varchar(6)), 2) as numeric(3,2))
from @temp1;

这可行,但后来我想如果 value1 中有多行并且所有行的长度都不同,而不是 6。我如何将 value1 的长度作为参数传递,如 cast(value1 as varchar(length of value1) ?

我尝试过声明一个变量 @length 并将其设置为等于 len(value1),然后将其作为 varchar(@length) 传递,但这不起作用。感谢您的帮助。

【问题讨论】:

  • 如果您只是在寻找小数点后的值,那么您可以转换为 varchar,然后获取小数点的 charIndex。然后根据该索引 + 1 将您的子字符串返回到强制转换值的长度。

标签: sql sql-server variables parameters casting


【解决方案1】:

我根本不会那样做。使用数学,特别是 MODULO。

declare @temp1 table (value1 numeric(5,2))
insert into @temp1 (value1)
values
(113.05)
, (911.123)
, (1.22)
, (.3)

select value1
    , UsingMath = value1 % 1
from @temp1;

【讨论】:

    猜你喜欢
    • 2021-01-07
    • 1970-01-01
    • 1970-01-01
    • 2020-03-10
    • 2013-11-11
    • 2015-07-27
    • 1970-01-01
    • 2019-05-07
    • 2013-03-16
    相关资源
    最近更新 更多