[英]trim sql variant
I have column sql variant, which has the following meanings: 100, 150, D1
I'm trying to convert all numbers in the columns into letters (such as D1
) according to specific logic in case when. 我有列sql变体,它具有以下含义:
100, 150, D1
我试图根据具体逻辑将列中的所有数字转换为字母(如D1
)。 But 150
has spaces and the CASE WHEN
doesn't work. 但
150
有空格, CASE WHEN
不起作用。
Here's the query I'm using: 这是我正在使用的查询:
Select *,
Case When LTrim(Cast(AttributeValue As NVarchar(Max))) Between 0 And 200 Then 'D1'
Else 'Other'
End
From MyTable As SCR With (NoLock);
I tried the following 我尝试了以下内容
LTRIM(CAST column AS VARCHAR(MAX))
but now I get error: 但现在我得到错误:
Conversion failed when converting the nvarchar value 'D1' to data type int
将nvarchar值'D1'转换为数据类型int时转换失败
How can I remove spaces from sql_variant? 如何从sql_variant中删除空格?
As per your comments edited to use BIGINT due to having larger numbers and leave the column the same if it is not BETWEEN 0 and 400 根据你的评论编辑使用BIGINT由于数字较大而且如果它不是BETWEEN 0和400则保持列相同
SELECT *
,CASE
WHEN ISNUMERIC(LTRIM(CAST(AttributeValue AS NVARCHAR(MAX)))) = 1
AND CAST(LTRIM(CAST(AttributeValue AS NVARCHAR(MAX))) AS BIGINT) BETWEEN 0 AND 400 THEN 'D1'
ELSE AttributeValue
END
FROM
MyTable AS SCR WITH (NOLOCK)
You can use the ISNUMERIC()
function to determine which of your sql_variants
are integers and which are not. 您可以使用
ISNUMERIC()
函数来确定哪些sql_variants
是整数,哪些不是。
The reason your code is failing isn't because of the trim it is because you are comparing a VARCHAR with an INTEGER so SQL is trying to automatically re cast your final string as an integer which in the case of D1 is not numeric so it causes a conversion error. 您的代码失败的原因不是因为它正在修改它,因为您正在将VARCHAR与INTEGER进行比较,因此SQL尝试自动将最终字符串重新转换为整数,在D1的情况下,它不是数字,因此它会导致转换错误。
Also note that you cannot use sql_variant
directly in the ISNUMERIC()
function so cast to a varchar
first. 另请注意,您不能直接在
ISNUMERIC()
函数中使用sql_variant
,因此ISNUMERIC()
转换为varchar
。
Here is an entire example of you to show you how it works: 以下是向您展示其工作原理的完整示例:
DECLARE @MyTable AS TABLE (AttributeValue SQL_VARIANT)
INSERT INTO @MyTable VALUES
(CAST(' 150' AS VARCHAR(100)))
,(CAST('D1' AS VARCHAR(100)))
SELECT *
,CASE
WHEN ISNUMERIC(LTRIM(CAST(AttributeValue AS NVARCHAR(MAX)))) = 1
AND CAST(LTRIM(CAST(AttributeValue AS NVARCHAR(MAX))) AS INT) BETWEEN 0 AND 200 THEN 'D1'
ELSE 'Other'
END
FROM
@MyTable AS SCR
使用sql替换函数select replace(columnnName,'','')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.