It is clear that omitting the length from a varchar is a bad thing . Unfortunately I am now working with a code base where this has happened. Extensively. I would like to correct this. The first step will be to find the occurrences. This is where I need help.
Searches on various web engines using all the synonyms I can think of return no authoritative answer. I'm asking for
- additional test cases which I've missed
- a comprehensive, canonical way of finding declarations without a length
Any technology which is typically available on a Windows development environment (SSMS, Powershell, .Net etc.) is good. Answers employing more niche technologies would be interesting for the wider community but less so for me personally.
### Tests ###
Since the four data types in question - char, nchar, varchar and nvarchar - all end with the characters C-H-A-R I use this alone in the tests below. This saves bloating the list and makes adding further tests simpler. It'll be easy enough to copy-paste-replace should the need arise.
-- These are all legal; the regex must not return these
char(9)
char (9) -- with a space
char (9) -- with a tab
char (9) -- tab space tab space
char(max)
char
(9) -- a new line between type and length
character(9)
CAST(999 AS character(9))
char varying(9)
character varying(9)
CAST(999 AS char varying(9))
CAST(999 AS character varying(9))
-- These also are legal; ugly, but legal
[char](9)
[char] (9) -- with a space
[char] (9) -- with a tab
[char] (9) -- tab space tab space
[char](max)
[char]
(9) -- a new line between type and length
-- The type can also be delimited by double-quote
"char"(9)
-- All the tests using square brackets should be duplicated with other delimiters.
[character](9)
CAST(999 AS [character](9))
-- SQL Server 2022 throws an error for [character varying]
-- Msg 243, Level 16, State 1, Line 15
-- Type character varying is not a defined system type.
-- These are business terms which the regex should not return
characteristic
charge
chart
-- These are valid SQL but missing the length. These are what the search should return
char;
char ; -- a space
char ; -- a tab
char,
char ,
char = 'lorem'
cast(9 as char)
convert(char, 9)
[char];
[char] ; -- a space
[char] ; -- a tab
[char],
[char] ,
[char] = 'lorem'
cast(9 as [char])
convert([char], 9)
character
CAST(999 AS character)
char varying
character varying
CAST(999 AS char varying)
CAST(999 AS character varying)
Asked by Michael Green
(25265 rep)
Jul 12, 2023, 12:32 PM
Last activity: Jul 20, 2023, 03:14 AM
Last activity: Jul 20, 2023, 03:14 AM