我想在从表中检索varchar时删除特定字符。查询如下所示:
SELECT ServiceName,
case isNumeric(Ramusage)
when 1 then
cast ( ltrim ( rtrim ( ramusage )) as int )
else
0
end as test,
priority
FROM ProcessInfo
这里的问题是ramusage是一个varchar,它存储的值为12,500K,4,321K。
这里我想从条目中删除k并单独显示数字。
答案 0 :(得分:4)
答案 1 :(得分:2)
使用REPLACE
DECLARE @ProcessInfo TABLE(
ServiceName VARCHAR(MAX),
Ramusage VARCHAR(MAX),
priority INT
)
INSERT INTO @ProcessInfo (ServiceName,Ramusage,priority)
SELECT 'TEST','12,123K',1
SELECT ServiceName,
case isNumeric(REPLACE(REPLACE(Ramusage,'K',''),',',''))
when 1 then
cast ( ltrim ( rtrim ( REPLACE(REPLACE(Ramusage,'K',''),',',''))) as int )
else
0
end as test,
priority
FROM @ProcessInfo
我们所做的是创建一个CLR函数来取一个字符串amd删除所有非数字项
[Microsoft.SqlServer.Server.SqlFunction]
public static SqlString RemoveNonNumeric(SqlString strValue)
{
string strNew = strValue.ToString();
char[] chrArray = strNew.ToCharArray();
strNew = null;
for (int iChar = 0; iChar < chrArray.Length; iChar++)
{
if (Char.IsNumber(chrArray[iChar]))
strNew += chrArray[iChar];
}
// Put your code here
return new SqlString(strNew);
}
答案 2 :(得分:0)
substr( ltrim( rtrim( ramusage ) ), length( ramusage ) - 1)
编辑 replace
,如下面的答案所述,效果更好。