Flexible use of 2 functions charindex and PATINDEX and wildcard characters
Functions: Charindex and PATINDEX
CHARINDEX: Checks if a character (string) is contained in another string, and returns the starting position of the specified expression in the string.
PATINDEX: Checks if a character (string) is contained in another string, returns the starting position of the first occurrence of a pattern in the specified expression, or zero if the pattern is not found in all valid text and character data types. Special: You can use wildcard characters!
Example:
1. Whether the query string contains non-numeric characters
SELECT PATINDEX ('%[^0-9]% ', ' 1235x461 ')
SELECT PATINDEX ('%[^0-9]% ', ' 12350461 ')
2. Whether the query string contains numeric characters
SELECT PATINDEX ('%[0-9]% ', ' Suyllgoo ')
SELECT PATINDEX ('%[0-9]% ', ' suyllg0o ')
3. Function judgment string contains only numbers
CREATE FUNCTION [Dbo].fn_isnumeric
(
@pString VARCHAR (8000)
)
RETURNS bit
With encryption
As
BEGIN
DECLARE @vJudge int
SET @vJudge = 0
SELECT @vJudge =
Case
When PATINDEX ('%[0-9]% ', LOWER (@pString)) > 0 Then 0
When PATINDEX ('%[0-9]% ', LOWER (@pString)) = 0 Then 1
END
RETURN @vJudge
END
4. Function judgment string contains only letters (ignoring case)
CREATE FUNCTION [Dbo].fn_isalpha
(
@pString VARCHAR (8000)
)
RETURNS bit
With encryption
As
BEGIN
DECLARE @vJudge int
SET @vJudge = 0
SELECT @vJudge =
Case
When PATINDEX ('%[a-z]% ', LOWER (@pString)) > 0 Then 0
When PATINDEX ('%[a-z]% ', LOWER (@pString)) = 0 Then 1
END
RETURN @vJudge
END
5. Function judgment string does not contain any symbols (including spaces)
CREATE FUNCTION [Dbo].fn_isalphanumeric
(
@pString VARCHAR (8000)
)
RETURNS bit
With encryption
As
BEGIN
DECLARE @vJudge int
SET @vJudge = 0
SELECT @vJudge =
Case
When PATINDEX ('%[^a-z0-9]% ', LOWER (@pString)) > 0 Then 0
When PATINDEX ('%[^a-z0-9]% ', LOWER (@pString)) = 0 Then 1
END
RETURN @vJudge
END
6. Function judgment string does not contain any symbols (except empty)
CREATE FUNCTION [Dbo].fn_isalphanumericblank
(
@pString VARCHAR (8000)
)
RETURNS bit
With encryption
As
BEGIN
DECLARE @vJudge int
SET @vJudge = 0
SELECT @vJudge =
Case
When PATINDEX ('%[^a-z0-9]% ', LOWER (@pString)) > 0 Then 0
When PATINDEX ('%[^a-z0-9]% ', LOWER (@pString)) = 0 Then 1
END
RETURN @vJudge
END
-Note: There is a last space in [^a-z0-9] mode.
With CHARINDEX ()--charindex (character, string) >0–> contains
Methods in SQL to determine how characters are contained in a string