Select only string with number SQL Server - sql-server

I need select only strings in my table, but this table has numbers and strings together.
Ex:
ID Name
1 Jacke11
2 Andre
3 Rodrigo11
4 55555
My select need return only Ids: 1, 2, 3.
Thanks

SELECT ID
FROM YourTable
WHERE ISNUMERIC(Name + '.0e0') = 0

As an alternative to Joe's very fine ISNUMERIC solution, you can use PATINDEX to make sure you have an alpha character:
SELECT ID
FROM YourTable
WHERE PATINDEX('%[a-z]%', name) > 0
This may be slightly faster since it will stop searching the string as soon as it gets to the first alpha character.

Related

Count of numbers followed by pipe symbol in a single data of a column in SQL Server

LEN(Column)-len(Replace(Column,'|','') will give total count of Pipe available in a single row data of a SQL Server.
But I need to count the number of records that has Pipe Symbol followed immediately to Number,
**Eg 1:** MNY-THY-**2|** *YUI_WER-NA|JIU-ERT-**8|***
The output of the above record is 2.
**Eg 2:** *MNY-YU-NA|*
The output is 0
**Eg 3:** *MNY-9876**5|***
The output is 1
UPDATE TO MY QUESTION BASED ON ANSWERS SUGGESTED:
**Eg 4:** MNY-YU-1234
The output is 0 Since there is no '|' symbol in my example 4, the result should be 0 only.
Any suggestion would be highly supportable.
You can Split the String based on the "|" and Check the value from the right Side whether it contains number or not.
DECLARE #tosearch VARCHAR(MAX)='%[0-9]|%' ,#string VARCHAR(MAX)='FGL_NU_0003'
SELECT COUNT(CASE WHEN RIGHT(VALUE,1) LIKE '[0-9]' THEN 1 ELSE NULL END)
FROM STRING_SPLIT(#string,'|')
WHERE #string LIKE '%|%'
Expected Output:
MNY-YU-1234 - 0
If you are using SQL Server 2016+, STRING_SPLIT() is an option:
Table:
SELECT *
INTO Data
FROM (VALUES
('MNY-THY-2| YUI_WER-NA|JIU-ERT-8|'),
('MNY-YU-NA|'),
('MNY-98765|'),
('FGL_NU_0003')
) v (TextData)
Statement:
SELECT *
FROM Data d
OUTER APPLY (
SELECT COUNT(*) AS NumberCount
FROM STRING_SPLIT(d.TextData, '|') s
WHERE (d.TextData LIKE '%|%') AND (RIGHT(s.[value], 1) LIKE '[0-9]')
) a
Result:
TextData NumberCount
MNY-THY-2| YUI_WER-NA|JIU-ERT-8| 2
MNY-YU-NA| 0
MNY-98765| 1
FGL_NU_0003 0

!IsNullOrEmpty equivalent in SQL server

I'm creating an SSRS report and during writing the query I look up the code logic for the data that needs to be retrieved in query. There is lots of usage of !String.IsNullOrEmpty method so I want to know what is the shortest and best way to do the equivalent check in SQL server?
WHERE t.Name IS NOT NULL OR T.Name != ''
or....
WHERE LEN(t.Name) > 0
which one is correct? Or is there any other alternative?
There is no built-in equivalent of IsNullOrEmpty() in T-SQL, largely due to the fact that trailing blanks are ignored when comparing strings. One of your options:
where len(t.Name) > 0
would be enough as len() ignores trailing spaces too. Unfortunately it can make the expression non-SARGable, and any index on the Name column might not be used. However, this one should do the trick:
where t.Name > ''
P.S. For the sake of completeness, the datalength() function takes all characters into account; keep in mind however that it returns the number of bytes, not characters, so for any nvarchar value the result will be at least double of what you might expect (and with supplementary characters / surrogate pairs the number should be even higher, if my memory serves).
If the desired result is the simplest possible one-liner then:
WHERE NULLIF(Name, '') IS NOT NULL
However, from a performance point of view following alternative is SARGable, therefore indexes potentially can be used to spot and filter out records with such values
WHERE Name IS NOT NULL AND Name != ''
An example:
;WITH cte AS (
SELECT 1 AS ID, '' AS Name UNION ALL
SELECT 2, ' ' UNION ALL
SELECT 3, NULL UNION ALL
SELECT 4, 'abc'
)
SELECT * FROM cte
WHERE Name IS NOT NULL AND Name != ''
Results to:
ID Name
---------
4 abc
Yes, you can use WHERE LEN(t.Name)>0.
You can also verify as below:
-- Count the Total number of records
SELECT COUNT(1) FROM tblName as t
-- Count the Total number of 'NULL' or 'Blank' records
SELECT COUNT(1) FROM tblName as t WHERE ISNULL(t.Name,'')= ''
-- Count the Total number of 'NOT NULL' records
SELECT COUNT(1) FROM tblName as t WHERE LEN(t.Name)>0
Thanks.

How can determine and avoid records based on its left most String values are numeric in SQL Query?

I have a table AgentDetail, and I need to create a query which returns only records which contain left most 5 numeric digits.
The table has 3 columns
AgentId, AgentName, AgentTextCode
where in the AgentTextCode column, there could be 5 digits or any text value (sometime 2 bytes chars). So output records should be only those which have a value which starts with 5 numeric digits (decimal value not possible).
Sample data & output:
We can use LIKE here:
SELECT
AgentID, AgentName, AgentTextCode
FROM yourTable
WHERE AgentTextCode LIKE '[0-9][0-9][0-9][0-9][0-9]%';
SQL Server's LIKE operator supports some primitive regex capabilities, as shown above.
You can use IsNumeric and Substring from TSQL:
SELECT
AgentID, AgentName, AgentTextCode
FROM yourTable
WHERE ISNUMERIC(Replace(Replace(substring(AgentTextCode, 1, 5),'+','A'),'-','A') + '.0e0') = 1;
GO
Reference here:
CAST and IsNumeric

Data manipulation using SQL Server Substring so something else

I have a table A like this:
ID Col1
----------------------
1 xyz-abcccc
2 xyz-jkasdasd
3 abcds-asks
4 asdasdasda-as
I want to get output like this:
ID Col1
-------------
1 abcccc
2 jkasdasd
3 asks
4 as
I want get output where anything before the dash - is ignored.
Thanks
charindex() would be a good place to start. The only trick is add a dash within the charindex function as a fail-safe thus avoids throwing an error.
Example
Select ID
,Col1 = substring(Col1,charindex('-',col1+'-')+1,len(Col1))
from YourTable
Returns
ID Col1
1 abcccc
2 jkasdasd
3 asks
4 as
You can use a combination of RIGHT and CHARINDEX functions as well.
Query
select [ID],
case when [Col1] like '%-%' then right([Col1], charindex('-', reverse([Col1]), 1) - 1)
else [Col1] end as [new_col1]
from [your_table_name];

how to skip Numbers in Sql Server using Order by

I have sql query which returns the following Result :
select * from Emp Order By EmpName asc
Result :
Empid EmpName
1 1
2 2
3 3
A ALL
N NOTALL
but I want output like below :
Empid EmpName
A ALL
N NOTALL
1 1
2 2
3 3
how can I achieve this...
Define a custom sort order either like this:
select *
from Emp
Order By
CASE WHEN IsNumeric(EmpName) = 1 then 0 else 1 end asc,
Empid
or by adding an explict SortOrder column to the table
[Note: ISNUMERIC returns 1 for some characters that are not
numbers, such as plus (+), minus (-), and valid currency symbols such
as the dollar sign ($). For a complete list of currency symbols, see
Using Monetary Data.]
Use a custom sorting logic in your ordering something like:
ORDER BY
CASE
WHEN EMPID = 'A' THEN 1
WHEN EMPID = 'N' THEN 2
ELSE CAST(EMPID AS INT) + 2
END
You could also use the ISNUMERIC function as described in Mitch Wheat's answer to avoid explicitly declaring the cases. However, in case you have a non-alphabetical order e.g. 'G' should appear before 'A', then it would be good to explicitly specify the values.

Resources