SQL Server LIKE containing bracket characters(Variable) - sql-server

How can I search in a letter in variable like this 🔽
Where Name Like '%#Variable%'

Hello #ahmad_lababidi welcome to stackoverflow,
If it is not an ASCII character and generally requires a column of type NVARCHAR and a literal with string N '' (Except when the encoding accepts symbols)
for example, the UNICODE code of your character is 55357, so you can search for this character in your query, as in the following example.
CREATE TABLE #FIND (NAME nvarchar(10));
INSERT INTO #FIND VALUES (N'🔽');
SELECT UNICODE(N'🔽') --> 55357
SELECT *
FROM #FIND
WHERE NAME LIKE '%' + NCHAR(55357) + '%'

You need to use an nvarchar instead, and make sure you prefix your literal string with an N to denote that the literal string is an nvarchar:
DECLARE #variable varchar(1) = N'🔽';
SELECT *
FROM YourTable
WHERE YourColumn LIKE N'%' + #variable + N'%';

Related

Function to remove all Non-alpha-numeric characters, superscripts, and subscripts, except a dash '-'

I need to create a T-SQL function that only keeps a hyphen (dash '-') and removes all non-alphanumeric characters (plus all spaces, superscripts and subscripts) from a given string.
You can test Superscript/Subscripts in SSMS:
select 'Hello® World™ '
Example:
input string
output string:
HelloWorld-ThisIsATest123
Any solutions or thoughts will be appreciated.
Check this link. This removes all alpha numeric characters. You can include '-' also to the included list.
How to strip all non-alphabetic characters from string in SQL Server?
In this example for the answer from #George Mastros, use '%[^a-zA-Z0-9-]%' for regular expression instead of '%[^a-z]%'
Here is the reformatted function to include '-' and numeric characters:
-- Reformatted function
Create Function [dbo].[RemoveNonAlphaCharacters](#Temp VarChar(1000))
Returns VarChar(1000)
AS
Begin
Declare #KeepValues as varchar(50)
Set #KeepValues = '%[^a-zA-Z0-9\-]%'
While PatIndex(#KeepValues, #Temp) > 0
Set #Temp = Stuff(#Temp, PatIndex(#KeepValues, #Temp), 1, '')
Return #Temp
End
--Call function
Select dbo.RemoveNonAlphaCharacters('Hello® World™ -123 !##$%^')
OUTPUT: HelloWorld-123
I identified my code's issue - I previously had exact same function which was NOT removing superscript / subscript, and I was wondering why. Here was the issue: The input/output datatype should NOT be NVARCHAR , but mere varchar, else it will contain superscripts in the return string:
problem code :
Create Function [dbo].[RemoveNonAlphaCharacters](#Temp NVarChar(1000))
Returns NVarChar(1000)
AS
...

How to convert TIMESTAMP values to VARCHAR in T-SQL as SSMS does?

I am trying to convert a TIMESTAMP field in a table to a string so that it can be printed or executed as part of dynamic SQL. SSMS is able to do it, so there must be a built-in method to do it. However, I can't get it to work using T-SQL.
The following correctly displays a table result:
SELECT TOP 1 RowVersion FROM MyTable
It shows 0x00000000288D17AE. However, I need the result to be part of a larger string.
DECLARE #res VARCHAR(MAX) = (SELECT TOP 1 'test' + CONVERT(BINARY(8), RowVersion) FROM MyTable)
PRINT(#res)
This yields an error: The data types varchar and binary are incompatible in the add operator
DECLARE #res VARCHAR(MAX) = (SELECT TOP 1 'test' + CONVERT(VARCHAR(MAX), RowVersion) FROM MyTable)
PRINT(#res)
This results in garbage characters: test (®
In fact, the spaces are just null characters and terminate the string for the purpose of running dynamic SQL using EXEC().
DECLARE #sql VARCHAR(MAX) = 'SELECT TOP 1 ''test'' + CONVERT(VARCHAR(MAX), RowVersion) FROM MyTable'
EXEC (#sql)
This just displays a table result with the word "test". Everything after "test" in the dynamic SQL is cut off because the CONVERT function returns terminating null characters first.
Obviously, what I want the resultant string to be is "test0x00000000288D17AE" or even the decimal equivalent, which in this case would be "test680335278".
Any ideas would be greatly appreciated.
SELECT 'test' + CONVERT(NVARCHAR(MAX), CONVERT(BINARY(8), RowVersion), 1). The trick is the 1 to the CONVERT as the style, per the documentation. (Pass 2 to omit the 0x.)
As mentioned in the comments, the undocumented function master.sys.fn_varbintohexstr will convert binary to string such that you could then concatenate with some other string value:
DECLARE #binary BINARY(8)
SELECT #binary = CAST(1234567890 AS BINARY(8))
SELECT #binary AS BinaryValue,
LEFT(master.sys.fn_varbintohexstr(#binary),2) + UPPER(RIGHT(master.sys.fn_varbintohexstr(#binary),LEN(master.sys.fn_varbintohexstr(#binary))-2)) AS VarcharValue,
'test' + LEFT(master.sys.fn_varbintohexstr(#binary),2) + UPPER(RIGHT(master.sys.fn_varbintohexstr(#binary),LEN(master.sys.fn_varbintohexstr(#binary))-2)) AS ConcatenatedVarcharValue
I went ahead and split the first two characters and did not apply the UPPER function to them, to exactly reproduce the format as displayed when a binary value.
Results:
/--------------------------------------------------------------------\
| BinaryValue | VarcharValue | ConcatenatedVarcharValue |
|--------------------+--------------------+--------------------------|
| 0x00000000499602D2 | 0x00000000499602D2 | test0x00000000499602D2 |
\--------------------------------------------------------------------/
Have a look at this:
SELECT
substring(replace(replace(replace(replace(cast(CAST(GETDATE() AS datetime2) as
varchar(50)),'-',''),' ',''),':',''),'.',''),1,18)

Find strings in non alphabetic strings

I have to find all occurence of alphabetic strings in table. To do it, I use below algorithm (I iterate through another table in loop to get this #TableName value):
UPPER(rows_value) like '%' + #TableName + '%')
This condition is wrong because it's also shows me string contained in another string.
Let's assume that #TableName = test. I would like to find records in table, which contains this string (also surrended by non alphabetical characters). My algorithm returns me rows contained:
test
(test)
test0x
test02
_test_2222
pretest <---
uptest <----
...
I don't need last two, because these are different words. How to modify my condition to exclude non needed results?
Try next query:
DECLARE #TableName VARCHAR(128) = 'test' -- Replace with propper data type and max length
SELECT *
FROM (VALUES
('test'),
('(test)'),
('test0x'),
('test02'),
('_test_2222'),
('pretest '),
('uptest'),
('testAlpha'),
('13223 tes3432')
) t(Col1)
WHERE t.Col1 LIKE '%' + #TableName + '%'
AND NOT(t.Col1 LIKE '%[a-z]' + #TableName + '%' OR t.Col1 LIKE '%' + #TableName + '[a-z]%')

How can I search for a sequence of bytes in SQL Server varbinary(max) field?

I am trying to write a query on SQL Server 2012 that will return varbinary(max) columns that contain a specified byte sequence. I am able to do that with a query that converts the varbinary field to varchar and uses LIKE:
SELECT * FROM foo
WHERE CONVERT(varchar(max), myvarbincolumn) LIKE
'%' + CONVERT(varchar(max), 0x626C6168) + '%'
where "0x626C6168" is my target byte sequence. Unfortunately, this works only if the field does not contain any bytes with the value zero (0x00) and those are very common in my data. Is there a different approach I can take that will work with values that contain zero-valued bytes?
If you use a binary collation it should work.
WITH foo(myvarbincolumn) AS
(
SELECT 0x00626C616800
)
SELECT *
FROM foo
WHERE CONVERT(VARCHAR(max), myvarbincolumn) COLLATE Latin1_General_100_BIN2
LIKE '%' + CONVERT(VARCHAR(max), 0x626C6168) + '%'
You might need (say) Latin1_General_BIN if on an older version of SQL Server.
Unfortunately the solution proposed by Martin has a flaw.
In case the binary sequence in the search key contains any 0x25 byte, it will be translated to the % character (according to the ASCII table).
This character is then interpreted as a wildcard in the like clause, causing many unwanted results to show up.
-- A table with a binary column:
DECLARE #foo TABLE(BinCol VARBINARY(MAX));
INSERT INTO #foo (BinCol) VALUES (0x001125), (0x000011), (0x001100), (0x110000);
-- The search key:
DECLARE #key VARBINARY(MAX) = 0x1125; -- 0x25 is '%' in the ASCII table!
-- This returns ALL values from the table, because of the wildcard in the search key:
SELECT * FROM #foo WHERE
CONVERT(VARCHAR(max), BinCol) COLLATE Latin1_General_100_BIN2
LIKE ('%' + CONVERT(VARCHAR(max), #key) + '%');
To fix this issue, use the search clause below:
-- This returns just the correct value -> 0x001125
SELECT * FROM #foo WHERE
CHARINDEX
(
CONVERT(VARCHAR(max), #key),
CONVERT(VARCHAR(max), BinCol) COLLATE Latin1_General_100_BIN2
) > 0;
I just discovered this very simply query.
SELECT * FROM foo
WHERE CONVERT(varchar(max), myvarbincolumn,2) LIKE '%626C6168%'
The characters 0x aren't added to the left of the converted result for style 2.
https://learn.microsoft.com/en-us/sql/t-sql/functions/cast-and-convert-transact-sql?view=sql-server-ver16#binary-styles

Using variable in SQL LIKE statement

I've got a sproc (MSSQL 2k5) that will take a variable for a LIKE claus like so:
DECLARE #SearchLetter2 char(1)
SET #SearchLetter = 't'
SET #SearchLetter2 = #SearchLetter + '%'
SELECT *
FROM BrandNames
WHERE [Name] LIKE #SearchLetter2 and IsVisible = 1
--WHERE [Name] LIKE 't%' and IsVisible = 1
ORDER BY [Name]
Unfortunately, the line currently running throws a syntax error, while the commented where clause runs just fine. Can anyone help me get the un-commented line working?
If you are using a Stored Procedure:
ALTER PROCEDURE <Name>
(
#PartialName VARCHAR(50) = NULL
)
SELECT Name
FROM <table>
WHERE Name LIKE '%' + #PartialName + '%'
Joel is it that #SearchLetter hasn't been declared yet? Also the length of #SearchLetter2 isn't long enough for 't%'. Try a varchar of a longer length.
As Andrew Brower says, but adding a trim
ALTER PROCEDURE <Name>
(
#PartialName VARCHAR(50) = NULL
)
SELECT Name
FROM <table>
WHERE Name LIKE '%' + LTRIM(RTRIM(#PartialName)) + '%'
But in my opinion one important thing.
The "char(number)" it's lenght of variable.
If we've got table with "Names" like for example [Test1..Test200] and we declare char(5) in SELECT like:
DECLARE #variable char(5)
SET #variable = 'Test1%'
SELECT * FROM table WHERE Name like #variable
the result will be only - "Test1"! (char(5) - 5 chars in lenght; Test11 is 6 )
The rest of potential interested data like [Test11..Test200] will not be returned in the result.
It's ok if we want to limit the SELECT by this way.
But if it's not intentional way of doing it could return incorrect results from planned
( Like "all Names begining with Test1..." ).
In my opinion if we don't know the precise lenght of a SELECTed value, a better solution could be something like this one:
DECLARE #variable varchar(max)
SET #variable = 'Test1%'
SELECT * FROM <table> WHERE variable1 like #variable
This returns (Test1 but also Test11..Test19 and Test100..Test199).
This works for me on the Northwind sample DB, note that SearchLetter has 2 characters to it and SearchLetter also has to be declared for this to run:
declare #SearchLetter2 char(2)
declare #SearchLetter char(1)
Set #SearchLetter = 'A'
Set #SearchLetter2 = #SearchLetter+'%'
select * from Customers where ContactName like #SearchLetter2 and Region='WY'
DECLARE #SearchLetter2 char(1)
Set this to a longer char.
We can write directly too...
DECLARE #SearchLetter CHAR(1)
SET #SearchLetter = 'A'
SELECT *
FROM CUSTOMERS
WHERE CONTACTNAME LIKE #SearchLetter + '%'
AND REGION = 'WY'
or the following way as well if we have to append all the search characters then,
DECLARE #SearchLetter CHAR(1)
SET #SearchLetter = 'A' + '%'
SELECT *
FROM CUSTOMERS
WHERE CONTACTNAME LIKE #SearchLetter
AND REGION = 'WY'
Both these will work
I had also problem using local variables in LIKE.
Important is to know: how long is variable.
Below, ORDER_NO is 50 characters long, so You can not use: LIKE #ORDER_NO, because in the end will be spaces.
You need to trim right side of the variable first.
Like this:
DECLARE #ORDER_NO char(50)
SELECT #ORDER_NO = 'OR/201910/0012%'
SELECT * FROM orders WHERE ord_no LIKE RTRIM(#ORDER_NO)
It may be as simple as LIKE '%%[%3]%%' being [%3] the input variable.
This works for me with SAP B1 9.1
I ran into a similar problem. I needed to use just a small piece of a URL saved in my database where the front and ends were irrelevant.
I first attempted to use:
DECLARE #variable VARCHAR(250) = %x%;
SELECT * FROM tblone WHERE column1 LIKE '#variable'
However, this returned the error:
Arithmetic overflow error converting numeric to data type varchar
My working query was formatted:
DECLARE #variable VARCHAR(1000) = x;
SELECT * FROM tblone WHERE column1 LIKE '%'+#variable+'%'

Resources