Created
July 14, 2020 18:26
-
-
Save forstie/a4875e28704f2fc29cc9afdba7ab40f5 to your computer and use it in GitHub Desktop.
In a classic two-for-Tuesday move, another string based and built-in function solved question has come in.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- | |
-- Author: Scott Forstie | |
-- Date : July 14, 2020 | |
-- | |
-- Question: How can I use SQL to validate that a string only contains an approved list of characters? | |
-- Answer : The TRANSLATE() built-in function. | |
-- | |
-- TRANSLATE replaces the allowed characters with blanks. | |
-- Then, RTRIM throws all the blanks away. | |
-- Then, if the resulting LENGTH is zero, you can conclude that the string only contained allowed characters. | |
-- | |
create or replace variable toystore.sometext varchar(1000) for sbcs data; | |
set toystore.sometext = 'asldkfjj23949'; | |
-- length = 0 means that only allowed characters were used | |
values length(rtrim(TRANSLATE(toystore.sometext , | |
' ', | |
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890(+-*/%=_&"''()<>,.:;?) ' ))); | |
set toystore.sometext = 'asldkfj{}j23949'; | |
-- length > 0 means that only disallowed characters were used | |
values length(rtrim(TRANSLATE(toystore.sometext , | |
' ', | |
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890(+-*/%=_&"''()<>,.:;?) ' ))); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment