Sql server query for numbers inside a square bracket - sql-server

I have few formats of records in a table, ABCDEF, [123]ABCDEF, ABCDEF[ABC] and ABCDEF[123] Numbers of letters and digits are not fixed, they vary.
I can easily find the ones with brackets by something like this and it's variations.
SELECT * FROM X WHERE Y LIKE '%/[%' ESCAPE '/'
But I want to find the records where there are only three numbers inside the brackets and only if they appear at the beginning or ending of the line. i.e [123]ABCDEF and ABCDEF[123] formats.
I tried LIKE '%[___/]' ESCAPE '/' and hoped to manipulate it only accepting numbers inside the bracket but wasn't able to make it work.
A huge caveat is there might be records such as ABC[123]DEF format. This might troublesome because I don't want such records returned. I don't know if there are such records but I can't dismiss the possibility.
How can I do what I'm trying to do?

Brackets are used to provide valid set of characters. [0-9] means any digit from 0 to 9. If bracket is used literally, it must be escaped:
DECLARE #t TABLE(T nvarchar(20))
INSERT #t values ('ABCDEF'), ('[123]ABCDEF'), ('ABCDEF[ABC]'), ('ABCDEF[123]'), ('AS[123]AS')
SELECT *
FROM #t
WHERE T LIKE '\[[0-9][0-9][0-9]\]%' ESCAPE '\'
OR T LIKE '%\[[0-9][0-9][0-9]\]' ESCAPE '\'
--Or match anywhere
--WHERE T LIKE '%\[[0-9][0-9][0-9]\]%' ESCAPE '\'
Result
T
--------------------
[123]ABCDEF
ABCDEF[123]

Related

FOR XML PATH always adds trailing space to value

Using the FOR XML PATH structure to create a list of values,
I find that (annoyingly) it always adds a trailing space to selected values.
This ruins my attempts at providing my own delimiters - the trailing space is added after the column and delimiters have been concatenated.
For example:
SELECT country + '-' FROM countryTable...
results in the following string:
china- france- england-
Has anyone else seen this, and is there a way to stop it?
I don't think TRIM() will work, as that would be applied before the extra space is inserted...
I'm using SQL Server 2016.
Thanks
Ok, thanks to John C and his sample query I found the culprit.
I had a AS [data()] clause after the column name/delimiter.
Removing that removed the trailing space.
I don't know how/why but it did...
I suspect the data inside the country column, What if each value in Country column is having leading space. For XML PATH does not add any space to the data
Try this
SELECT RTRIM(LTRIM(country)) + '-' FROM countryTable...
You may have leading/trailing spaces and/or CRLFs. Perhaps this will help
Declare #countryTable table (country varchar(100))
Insert Into #countryTable values
(' china'), -- leading space
(char(13)+'france'), -- leading char(13)
(char(10)+'england') -- leading char(10)
Select Value=Stuff((Select Distinct '-' + ltrim(rtrim(replace(replace(country,char(13),''),char(10),'')))
From #countryTable
Where 1=1
For XML Path ('')),1,1,'')
Returns
Value
china-england-france
FOR XML PATH ... AS [data()] add to this from MS Help
If the path specified as column name is data(), the value is treated as an atomic value in the generated XML. A space character is added to the XML if the next item in the serialization is also an atomic value. This is useful when you are creating list typed element and attribute values.
When you write here ... AS something. Then something is used as open/closing markup tag for each selected value.
Add 2. Is possible concate in select clausule more fileds from each row. For other types than string type, value must be converted into string type CAST AS

How can I make LIKE match a number or empty string inside square brackets in T-SQL?

Is it possible to have a LIKE clause with one character number or an empty string?
I have a field in which I will write a LIKE clause (as a string). I will apply it later with an expression in the WHERE clause: ... LIKE tableX.FormatField .... It must contain a number (a single character or an empty string).
Something like [0-9 ]. Where the space bar inside square brackets means an empty string.
I have a table in which I have a configuration for parameters - TblParam with field DataFormat. I have to validate a value from another table, TblValue, with field ValueToCheck. The validation is made by a query. The part for the validation looks like:
... WHERE TblValue.ValueToCheck LIKE TblParam.DataFormat ...
For the configuration value, I need an expression for one numeric character or an empty string. Something like [0-9'']. Because of the automatic nature of the check, I need a single expression (without AND OR OR operators) which can fit the query (see the example above). The same check is valid for other types of the checks, so I have to fit my check engine.
I am almost sure that I can not use [0-9''], but is there another suitable solution?
Actually, I have difficulty to validate a version string: 1.0.1.2 or 1.0.2. It can contain 2-3 dots (.) and numbers.
I am pretty sure it is not possible, as '' is not even a character.
select ascii(''); returns null.
'' = ' '; is true
'' is null; is false
If you want exactly 0-9 '' (and not ' '), then you do to something like this (in a more efficient way than like):
where col in ('1','2','3','4','5','6','7','9','0') or (col = '' and DATALENGTH(col) = 0)
That's a tricky one... As far as I can tell, there isn't a way to do it with only one like clause. You need to do like '[0-9]' OR like ''.
You could accomplish this by having a second column in your TableX. That indicates either a second pattern, or whether or not to include blanks.
If I correctly understand your question, you need something that catches an empty string. Try to use the nullif() function:
create table t1 (a nvarchar(1))
insert t1(a) values('')
insert t1(a) values('1')
insert t1(a) values('2')
insert t1(a) values('a')
-- must select first three
select a from t1 where a like '[0-9]' or nullif(a,'') is null
It returns exactly three records: '', '1' and '2'.
A more convenient method with only one range clause is:
select a from t1 where isnull(nullif(a,''),0) like '[0-9]'

LIKE not working in TSQL

Consider this TSQL:
declare #b varchar(100)
set #b = 'BANK-41'
IF #b LIKE 'BANK_%'
BEGIN
print 'Wrong Matching'
END
Why does the TSQL match the string "BANK-" and "BANK_"?
In TSQL the underscore is a wildcard representing a single char.
In order to escape in you need to wrap it with square brackets, like this:
'BANK[_]%'
See this page:
http://www.dirigodev.com/blog/web-development-execution/escaping-percent-and-underscore-characters-in-t-sql-like-clause/
An underscore in SQL Server is reserved for a wild card character, I think. You need to escape it.I think you can put it in brackets:
%[_]%
You need to escape the "_". It is a special character for the Like statement. You can enclose it in [].
See LIKE (Transact-SQL).

How to escape quotes in strings in vertica (vsql)?

So I need to insert some values into a vertica database (via vsql), which may contain quotes and all sorts of special characters. But vertica does not seem to understand character escaping. For example:
rpt=> select "asdasda\"asdasdad" from some_table limit 1;
rpt"> ";
ERROR: syntax error at or near "" from some_table limit 1;
"" at character 26
LINE 1: select "asdasda\"asdasdad" from some_table limit 1;
This is not the insert statement, but you should get the idea.
Well, first off I should have used single quotes. Escape sequences used to work in earlier versions (before 4.0 I believe), but now they are off by default. If you do not want to tweak database config parameters you have two options.
Use E' syntax:
select E'somethin\' here' from v_catalog.dual_p;
Or double the quotes that need to be escaped:
select 'somethin'' here' from v_catalog.dual_p;

Strange behavior of sql server

I have following table structure in my DB
ID Name
--------------------------
ID_1 Name1
ID1 Name2
when I execute the following query
SELECT * FROM tblNames
WHERE ID LIKE '_1'
I get both records selected...
any suggestions how to get rid off it??
An underscore (_) is a special character in LIKE expressions that matches a single character.
To match an actual underscore, you need to escape it:
select * from tblNames where id like '%\_1' escape '\'
Here I'm telling SQL Server to consider backslash an escape character, and using it to escape the underscore.
Alternatively, you can represent the underscore as a character range with a single character in it - it will be interpreted literally in this case:
select * from tblNames where id like '%[_]1'
Which is a bit more succinct.
Reference: MSDN.
LIKE operator
Quickie: _ is a wildcard character that matches anything.
SELECT * FROM tblNames
WHERE ID LIKE '\_1' ESCAPE '\'
SELECT * FROM tblNames
WHERE ID LIKE '[_]1'
The underscore character is a wildcard for the like operator, and it matches any one character. In your case the pattern '_1' matches both '_1' and 'D1' in the data.
To use a literal underscore character in a pattern you need to put brackets around it so that it becomes a character range containing only one character:
SELECT * FROM tblNames
WHERE ID LIKE '[_]1'

Resources