[英]How to return only numbers from query where column is nvarchar
I have a simple query that is returning records where "column2" > 0 我有一个简单的查询,该查询返回“ column2”> 0的记录
Here is the data in the database 这是数据库中的数据
Column1 Column2
1 123456789
2 123456781
3 13-151-1513
4 alsdjf
5
6 000000000
Her is the query 她是查询
select column1, replace(a.Payroll_id,'-','')
from table1
where isnumeric(column2) = 1
I'd like to return the following: 我想返回以下内容:
Column1 Column2
1 123456789
2 123456781
3 131511513
This mean, I won't select any records when the column is blank (or null), will not return a row if it's not an integer, and will drop out the '-', and would not show row 6 since it's all 0. 这意味着,当列为空(或为空)时,我不会选择任何记录,如果它不是整数,则不会返回任何行,并且会舍弃“-”,并且由于其全为0而不会显示第6行。
How can I do this? 我怎样才能做到这一点?
I think you can use something like this : 我认为您可以使用以下方式:
USE tempdb
GO
CREATE TABLE #Temp
(
ID INT IDENTITY
,VALUE VARCHAR(30)
)
INSERT INTO #Temp (VALUE) VALUES ('1213213'), ('1213213'), ('121-32-13'), ('ASDFASF2123')
GO
WITH CteData
AS
(
SELECT REPLACE(VALUE,'-','') as Valor FROM #Temp
)
SELECT * FROM CteData WHERE (ISNUMERIC(Valor) = 1 AND valor not like '%[0-0]%')
DROP TABLE #Temp
then you can apply validations for empty, NULL,0 etc 那么您可以对empty,NULL,0等应用验证
If you are using SQL2012 or above you can also use TRY_PARSE
that is more selective in its parsing. 如果您使用的是SQL2012或更高版本,则还可以使用
TRY_PARSE
,它在解析时更具选择性。 This function will return NULL
if a record can't be converted. 如果无法转换记录,此函数将返回
NULL
。 You could use it like this: 您可以这样使用它:
CREATE TABLE #temp
(
ID INT IDENTITY ,
VALUE VARCHAR(30)
)
INSERT INTO #temp
( VALUE )
VALUES ( '1213213' ),
( '1213213' ),
( '121-32-13' ),
( 'ASDFASF2123' ),
( '0000000' )
SELECT ParsedValue
FROM #temp
CROSS APPLY ( SELECT TRY_PARSE(
Value AS INT ) AS ParsedValue
) details
WHERE ParsedValue IS NOT NULL
AND ParsedValue>0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.