How to set a string value into varbinary - sql

I'm using SQL Server and I'm trying to set a string into a varbinary without converting its value.
Example:
declare #string varchar(max)
set #string='0x7777'
update tablename
set Data=#string
I know this is not possible since it's not allowed. However I don't wanna convert the string to varbinary (using select CONVERT(varbinary(max),#string)) since it'll result in saving:
0x307837373737
Also, I know that making #string varbinary and removing ' 's would fix the problem, however that's not what I'm looking for since I'm working with strings in order to save it inside a varbinary.
I want the output to be: 0x7777 inside the varbinary
Thank you.

You can use CONVERT, just pass 3rd parameter.
update tablename
set Data=convert(varbinary(max), #string, 1)
If the data_type is a binary type, the expression must be a character
expression. The expression must be composed of an even number of
hexadecimal digits (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F, a,
b, c, d, e, f). If the style is set to 1 the characters 0x must be the
first two characters in the expression. If the expression contains an
odd number of characters or if any of the characters are invalid an
error is raised.
See reference for binary styles conversion.

Related

Error converting VarChar to VarBinary in SQL Server

I need to convert varchar to varbinary. The query I'm using is working correctly for only some values.
This one is working fine
SELECT CONVERT (VARBINARY(MAX), 'AFE27AF97DC6', 2)
while this one throws an error
Error converting data type varchar to varbinary
SELECT CONVERT (VARBINARY(MAX), 'AFEE27AF97DC6', 2)
I need to use style 2.
I've read all the similar questions but I couldn't find the solution. Any thought would help me. Thank you!
Hmm, AFEE27AF97DC6 is one nibble short and it seems like only full bytes are accepted. Try to zero pad it. E.g.
SELECT convert(varbinary(max), '0AFEE27AF97DC6', 2)
You can also wrap it in a CASE expression checking if the string has an even or odd length, should the strings be variable.
SELECT convert(varbinary(max),
CASE
WHEN len('AFEE27AF97DC6') % 2 <> 0 THEN
concat('0', 'AFEE27AF97DC6')
ELSE
'AFEE27AF97DC6'
END,
2)
(Replace the literals with your variable.)
This is pretty clearly stated in the documentation:
1, 2 [for the third argument]
For a binary data_type, the expression must be a character expression. The expression must have an even number of hexadecimal digits (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F, a, b, c, d, e, f).
Your first string has a length of 12, so it converts fine. The second has a length of 13, so it is not valid.
I am not sure what you intend, but a 0 in the 3rd position gives similar results for the two conversions:
SELECT CONVERT(varbinary(max),'AFE27AF97DC6' , 2), CONVERT(varbinary(max),'AF0EE27AF97DC6' , 2)
Gives:
0xAFE27AF97DC6 0xAF0EE27AF97DC6

Sql Server using Convert and Replace together in the same statement

I wanted to double check my logic for a query in SQL Server.
The idea is that I am able to feed the following values and it will make sure the result is a decimal with four trailing digits.
Possible values for #LABORQTY:
1,200
1,200.42
1200 (Integer)
1200.42
1200 (As a String)
1200.42 (As a String)
When the value is a string, it will give the error:
Error converting data type nvarchar to numeric.
Here is my code:
CONVERT(DECIMAL(12, 4), REPLACE(#LABORQTY, ',', ''))
The output each time though should be decimal:
1200.4200
Your question is really confused, but I'll answer according to the following parameters:
#laborqty is a VARCHAR
#laborqty may somehow come to contain any of the following values:
'1200'
'1200.42'
'1,200'
'1,200.42'
In which case CONVERT(DECIMAL(12, 4), REPLACE(#LABORQTY, ',', '')) will indeed produce a decimal with up to 4 digits of fractional precision. Whether your query tool/programming language will output it as 1200.4200 or not is another matter entirely; it might well just output 1200.42 and drop the trailing zeroes
If you're getting Error converting data type varchar to numeric. still, there is some other character data (not comma) in your numeric string
If you definitely want the trailing zeroes, format it into a string before you output
FORMAT(CONVERT(decimal(12,4), '1200.42'), '0.0000')
This will generate a string with 4 trailing zeroes
you can use :
select CAST ( REPLACE( '1,200.4' , ',','') AS decimal(17,4))

Why does it give an error when casting a string to GUID in SQL Server?

This is a simple issue.. I have two statements in sql server:
Case 1) select cast('d8b673a9-816c-4f45-b446-158b3e65fb45' as uniqueidentifier)
**Result in this case:**
D8B673A9-816C-4F45-B446-158B3E65FB45
Case 2) select cast('g448d9e5-1499-25dc-er45-254717c234g8' as uniqueidentifier)
**Result in this case:**
Conversion failed when converting from a character string to uniqueidentifier.
As you can see there is clearly no difference between the two guids..
A GUID should not contain an 'r' or a 'g',only Hexadecimal digits, which is why your second string will not cast.
See info here:
https://en.wikipedia.org/wiki/Hexadecimal
In mathematics and computing, hexadecimal (also base 16, or hex) is a positional numeral system with a radix, or base, of 16. It uses sixteen distinct symbols, most often the symbols 0–9 to represent values zero to nine, and A, B, C, D, E, F (or alternatively a, b, c, d, e, f) to represent values ten to fifteen.

SQL get decimal with only 2 places with no round

I have a query (SQL Server) that returns a decimal. I only need 2 decimals without rounding:
In the example above I would need to get: 3381.57
Any clue?
You could accomplish this via the ROUND() function using the length and precision parameters to truncate your value instead of actually rounding it :
SELECT ROUND(3381.5786, 2, 1)
The second parameter of 2 indicates that the value will be rounded to two decimal places and the third precision parameter will indicate if actual rounding or truncation is performed (non-zero values will truncate instead of round).
Example
You can see an interactive example of this in action here.
Another possibility is to use TRUNCATE:
SELECT 3381.5786, {fn TRUNCATE(3381.5786,2)};
LiveDemo
If you want to control the representation, you need to output the value as a string. One method is to convert to a decimal and then to a string:
select cast(cast(total as decimal(10, 2)) as varchar(255))
Another method is to convert to a string using str(). However, this often requires the removal of spaces:
select replace(str(total, 10, 2), ' ', '')

Why TSQL convert a function's result in one way and a character string to other way?

I try this command in SQL Server 2005 to obtain a MD5 from '123':
select SUBSTRING(sys.fn_sqlvarbasetostr(HASHBYTES('MD5', '123' )), 3, 32)
and I get this result:
202cb962ac59075b964b07152d234b70
I want to convert to binary format,
select
convert(varbinary(16), SUBSTRING(sys.fn_sqlvarbasetostr(HASHBYTES('MD5', '123')), 3, 32))
And I get this result:
0x32003000320063006200390036003200
Why does this code:
select convert(varbinary(16), '202cb962ac59075b964b07152d234b70')
result in a different value?
0x32303263623936326163353930373562
"Regular Character Type" vs Unicode
This performs a conversion from Nvarchar(Unicode) to Varbinary
select convert(varbinary(16),SUBSTRING(sys.fn_sqlvarbasetostr(HASHBYTES('MD5', '123' )),3,32))
By default, putting text in single quotes uses regular character types like Char or Varchar. This performs a conversion from Varchar("Regular Data Type") to Varbinary
select convert(varbinary(16),'202cb962ac59075b964b07152d234b70')
Try this:
SELECT CONVERT(varbinary(16), N'202cb962ac59075b964b07152d234b70')
The "N" before the quote defines the value as Nvarchar(Unicode) and you get your desired value
0x32003000320063006200390036003200
Hope this helps!