Skip to content

Instantly share code, notes, and snippets.

@forstie
Created July 14, 2020 18:26
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save forstie/a4875e28704f2fc29cc9afdba7ab40f5 to your computer and use it in GitHub Desktop.
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.
--
-- 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