How do you set a binary value from a string variable comprised of a binary literal in SQL Server? - sql

I have a table with a column of binary literals converted to strings that I need to relate to a table containing the same value as binary(16)
Root table string Value '2F774578C33011E880D80050569C29CA'
table value I need to join to 0x2F774578C33011E880D80050569C29CA
is there a way to convert either the root table to Binary by simply adding the 0x to the string then declaring the string a literal value for the binary? or convert the binary to the string contained in the root.
I tried the following with no luck:
DECLARE #jobIDBinary Binary(16)
DECLARE #jobString Nvarchar(50)
SET #jobIDBinary = '0x'+
(SELECT TOP (1) JobId
FROM [Record])
error: Implicit conversion from data type nvarchar to binary is not allowed. Use the CONVERT function to run this query.
I also tried converting the other way:
DECLARE #convo varchar(max)
SET #convo = (SELECT TOP (1)
[BinaryJobID]
FROM [GAPClaims].[dbo].[Record2]
WHERE binaryjobId IS NOT NULL )
Results = ,]óJ¾¶‡Á§\ê€
Thanks ahead of time.

You can convert your varbinary to varchar, and join on it (or relate it, as you stated).
declare #v varbinary(16) = 0x2F774578C33011E880D80050569C29CA
select #v, convert(varchar(256), #v,2)
declare #s varchar(256) = '2F774578C33011E880D80050569C29CA'
select #s, convert(varbinary(16),#s,2)
So, for you:
DECLARE #convo varchar(max)
SET #convo = (SELECT TOP (1)
convert(varchar(256),[BinaryJobID],2)
FROM [GAPClaims].[dbo].[Record2]
WHERE binaryjobId IS NOT NULL )
See the Binary section in the docs for why I used 2 in the convert statement.

Try this to convert string to binary:
CONVERT(BINARY(16), #jobString)
and Reverse:
CONVERT(VARCHAR(max), #jobBinary)

Related

How can varchar containing integer work in calculations

How come string can contain integer. Even if I assume string storing numeric values as string, but even i can use in it calculation and getting the result as well. Just to try I wrote 5 in inverted commas and still calculation works fine. Not sure how?
declare #x varchar(20)
declare #y int
select #x='5'
select #y=6
select #x+#y
SQL Server -- and all other databases -- convert values among types when the need arises.
In this case, you have + which can be either string concatenation or number addition. Because one argument is an integer, it is interpreted as addition, and SQL Server attempts to convert the string to a number.
If the string cannot be converted, then you will get an error.
I would advise you to do your best to avoid such implicit conversions. Use the correct type when defining values. If you need to store other types in a string, use cast()/convert() . . . or better yet, try_cast()/try_convert():
try_convert(int, #x) + #y
A varchar can contain any character from the collations codepage you are using. For the purposes of this answer, I'm going to assume you're using something like the collation SQL_Latin1_General_CP1_CI_AS (which doesn't have any "international" characters, like Kanji, Hiragana, etc).
You first declare the variable #x as a varchar(20) and put the varchar value '5' in it. This is not an int, it's a varchar. This is an important distinction as a varchar and a numerical data type (like an int) behave very differently. For example '10' has a lower value than '2', where as the opposite is true for 10 and 2. (This is one reason why using the correct data type is always important.)
Then the second variable you have is #y, which is an int and has the value 6.
Then you have your expression SELECT #x+#y;. This has 2 parts to it. Firstly, as you have 2 datatypes, Data Type Precedence comes into play. int has a higher precedence than a varchar, and so #x is implicitly converted to an int. Then the expression is calculated, uses + as an addition operator (not a concatenation operator). Therefore the expression is effectively derived like this:
#x + #y = '5' + 6 = CONVERT(int,'5') + 6 = 5 + 6 = 11
SQL Server uses the following precedence order for data types:
user-defined data types (highest)
sql_variant
xml
datetimeoffset
datetime2
datetime
smalldatetime
date
time
float
real
decimal
money
smallmoney
bigint
int
smallint
tinyint
bit
ntext
text
image
timestamp
uniqueidentifier
nvarchar (including nvarchar(max) )
nchar
varchar (including varchar(max) )
char
varbinary (including varbinary(max) )
binary (lowest)

Difficulty printing one particular query in MSSQL

I'm trying to construct a small query which will pull data from individual fields in a DB and print them in a human readable list format (it's what the operators are used to seeing). The code I have here is far from complete but It seems to me that it should work.
DECLARE #PSUCARD VARCHAR(20)
DECLARE #EQUIPMENT VARCHAR(50)
DECLARE #T1 VARCHAR
SET #PSUCARD = 'PSU-888'
SET #EQUIPMENT = '123_POUCH'
PRINT #PSUCARD + ':'
PRINT #EQUIPMENT
PRINT ''
IF (SELECT TEMPERATURE_MAIN FROM PSU WHERE PSU.PART_ID = #PSUCARD AND PSU.OPERATION_RESOURCE_ID = #EQUIPMENT)IS NOT NULL BEGIN
SET #T1 = (SELECT TEMPERATURE_MAIN FROM PSU WHERE PSU.PART_ID = #PSUCARD AND PSU.OPERATION_RESOURCE_ID = #EQUIPMENT)
PRINT 'Temperature: ' + #T1
--(SELECT TEMPERATURE_MAIN FROM PSU WHERE PSU.PART_ID = #PSUCARD AND PSU.OPERATION_RESOURCE_ID = #EQUIPMENT)
END
If I execute the code as is, #T1 returns a * rather than a value. If I remove comments from the line below I am reassured that there is indeed a value there.
I have other code very similar to this which works fine. Any ideas?
Also, I don't know if this helps in diagnosing the problem, but despite the temperature field in the DB being an INT, I get a conversion message if I try to treat #T1 an an INT.
This is because you declared #T1 as VARCHAR without a length. According to this:
When n is not specified in a data definition or variable declaration
statement, the default length is 1. When n is not specified when using
the CAST and CONVERT functions, the default length is 30.
You should always specify a length when declaring a VARCHAR variable:
DECLARE #T1 VARCHAR(50)
You need to give length for varchar datatype else it is going to take only one character
DECLARE #T1 VARCHAR(50)

Why does string variable store only first symbol?

Can anyone tell me why the LikeString variable is always % ? Here's the code:
DECLARE #LikeString NVARCHAR = CAST('%4075%' AS nvarchar)
SELECT #LikeString
I've tried this in SQL Server 2008 R2 and SQL Server 2012, but #LikeString always contains % instead of %4075% as I expected.
for char, varchar, nchar, nvarchar
When size is not specified in variable declaration statement, the default length is 1
DECLARE #LikeString NVARCHAR(6) = CAST('%4075%' AS nvarchar(6))
SELECT #LikeString
or simpler:
DECLARE #LikeString NVARCHAR(6) = N'%4075%'
SELECT #LikeString
From the SQL Server 2008 R2 Transact-SQL documentation...
"When n is not specified in a data definition or variable declaration statement, the default length is 1. When n is not specified with the CAST function, the default length is 30."
https://msdn.microsoft.com/en-us/library/ms186939(v=sql.105).aspx
You are using a variable declaration statement, therefore all but the first character is being truncated from the string when you attempt to initialize the variable with "%4075%".
Therefore, as others have stated, the solution is to specify the length of your nvarchar data type variable.
Use this:
DECLARE #LikeString NVARCHAR(50) = CAST('%4075%' AS nvarchar(50))
SELECT #LikeString

SQL Server compare varchar field with binary(16)

I have 2 tables - Table A with primary key column of type binary(16) and another table B with foreign key referring to the same column but with data type as varchar(50). So table A has values like 0x0007914BFFEC4603A6900045492EFA1A and table B has the same value stored as 0007914BFFEC4603A6900045492EFA1A.
How do i compare these 2 columns, which would give me
0007914BFFEC4603A6900045492EFA1A = 0x0007914BFFEC4603A6900045492EFA1A
You will need to convert the binary(16) to a string. A sample of how to do this can be found in the question below. This question converts a varbinary to a string, but the same technique can be used for a binary column or variable:
SQL Server converting varbinary to string
Example code for how to do this is below:
declare #bin binary(16), #str varchar(50)
set #bin = 0x0007914BFFEC4603A6900045492EFA1A
set #str = '0007914BFFEC4603A6900045492EFA1A'
select #bin as'binary(16)', #str as 'varchar(50)'
-- the binary value is not equal to the string value
-- this statement returns 'binary value is not equal to string'
if #bin = #str select 'binary value is equal to string'
else select 'binary value is not equal to string'
declare #binstr varchar(50)
select #binstr = convert(varchar(50), #bin, 2)
select #binstr
-- the converted string value matches the other string
-- the result of this statement is "converted string is equal"
if #binstr = #str select 'converted string is equal'
else select 'converted string is NOT equal'
To use this in a join, you can include the conversion in the ON clause of the inner join or in a WHERE clause:
select *
from TableA
inner join TableB
on TableB.char_fk = convert(varchar(50), TableA.bin_pk, 2)
UPDATE
For SQL Server 2005, you can use an XML approach shown by Peter Larsson here:
-- Prepare value
DECLARE #bin VARBINARY(MAX)
SET #bin = 0x5BAA61E4C9B93F3F0682250B6CF8331B7EE68FD8
-- Display the results
SELECT #bin AS OriginalValue,
CAST('' AS XML).value('xs:hexBinary(sql:variable("#bin"))', 'VARCHAR(MAX)') AS ConvertedString
You can also use the undocumented function sys.fn_varbintohexstr, but as this post on dba.stackexchange.com explains, there are several reasons why you should avoid it.
CONVERT with style 2 to get a binary representation of the hexadecimal string;
... where TableA.bin_pk = CONVERT(VARBINARY, TableB.char_fk, 2)
The correct aproach is to set both fields in the same datatype. in order to to do this create a new table say temp and use select into and convert:
select field1,...,convert(varchar(50),varbinary(16),fieldToConvert)...,fieldN
into myNewTable
Found the answer. I need to use
master.dbo.fn_varbintohexstr (#source)
which converts a varbinary to varchar, and then works perfectly well for comparison in my scenario.

T-SQL Len function not working as expected [duplicate]

This question already has an answer here:
Varchar variable is not working in WHERE clause
(1 answer)
Closed 9 years ago.
I'm working with Microsoft SQL Server (2008 R2 if that matters)
When I execute
select LEN('test')
I get 4 as expected
But now try this:
declare #s varchar
set #s='test'
select LEN(#s)
And the result is ... 1
How does it actually work?
That is because if you were to
SELECT #s
it would return
t
only. You need to specify the length.
From char and varchar (Transact-SQL)
When n is not specified in a data definition or variable declaration
statement, the default length is 1. When n is not specified when using
the CAST and CONVERT functions, the default length is 30.
SQL Fiddle DEMO
When you define this:
declare #s varchar
you get a varchar of exactly one character length .
There's absolutely nothing wrong with LEN!
What you need to do is specify an explicit length when you define your varchar variable
declare #s varchar(20)
set #s='test'
select LEN(#s)
Now you should get back 4 from LEN ...
Note: it is a recommend best practice to always specify a length when you use varchar - otherwise you'll run into these kind of surprises. ....
you have to declare it as nvarchar with more than 1 char
try this, it works:
declare #s nvarchar(100)