Convert nvarchar(max) to varbinary(max) - sql

Have table with values
report nvarchar(max) not null
description nvarchar(max)
In stored procedure I want select values from table and then convert it to varbinary max. I seletct :
select
CONVERT(varbinary(max), [report]) as [report],
ISNULL(CONVERT(varbinary(max), [description]), '') as [description]
from myTbl
but I get an error:
Implicit conversion from data type varchar to varbinary(max) is not allowed. Use the CONVERT function to run this query.
Please help me to solve this problem

The failure is occurring because you convert description to varbinary, but then try to cast any null values back to a varchar. You just need to move ISNULL inside the CONVERT or change the conversion value when null to a binary value.
ISNULL in CONVERT
SELECT
CONVERT(varbinary(MAX), report),
CONVERT(varbinary(max), ISNULL([description], '')) as [description]
FROM myTbl
Proper ISNULL Value
SELECT
CONVERT(varbinary(MAX), report),
ISNULL(CONVERT(varbinary(max), [description]), 0x) as [description]
FROM myTbl
Both versions will produce the same output 0x if description is null.

Related

How to cast varchar in varbinary?

I try to update column value by appending varchar strings.
MyTable{
Id int,
MyValueColumn varbinary(max),
MyParamColumn varchar(50)
}
how i append:
'{"ZoneId":'+cast ([MyValueColumn] as varchar)+', "ZoneName":"'+[MyParamColumn]+'"}'
And this return correct value:
'{"ZoneId":1018, "ZoneName":"szz"}'
But now i cast result in varbinary and cast it again in varchar (for check varbinary correcy):
cast (cast('{"ZoneId":'+cast ([MyValueColumn] as varchar)+', "ZoneName":"'+[MyParamColumn]+'"}' as varbinary) as varchar)
and result:
'{"ZoneId":1018
Whats can be wrong?
When you are using cast to varbinary without explicit specification of length default length is 30.
So some trimming of your data can occurs if you're using varbinary, not varbinary(n) or varbinary(max) explicitly.
See MSDN for reference.
NOTE:
Also you have missed ' in your query: cast (cast({"ZoneId":' should be cast (cast('{"ZoneId":'
Update
I've created simple example:
declare #text varchar(50)
select #text = '{"ZoneId":'+cast (1018 as varchar)+', "ZoneName":"'+'szz'+'"}'
select cast(cast(#text as varbinary) as varchar)
select cast(cast(#text as varbinary(max)) as varchar(max))
it gives you trimmed text in first cast and original untrimmed text when we're using varbinary(max)

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.

STORED PROCEDURE CONVERT ERROR

Have stored procedure where i want update data and want cast some varbinary to nvarchar
UPDATE [payterm].[dict_default_values]
SET [default_value] = CAST(#value AS NVARCHAR(MAX))
,[descr] = CAST(#descr AS NVARCHAR(MAX))
,[grp] = #grp
WHERE [code] = #code;
IF ##ROWCOUNT = 0
INSERT INTO [payterm].[dict_default_values]
([code], [default_value], [descr], [grp])
VALUES
(#code, #value, #descr, #grp);
When i put parametrs there were error : Implicit conversion from data type varchar to varbinary is not allowed. Use the CONVERT function to run this query
You also need to cast in the VALUES part of your INSERT statement.
Without knowing the data types of your variable/parameters/columns it's difficult to give a specific answer though.

Convert nvarchar to bigint in Sql server 2008

I want insert all rows of a table into another table, and I also want convert a nvarchar field into bigint, but when I use convert(bigint, col1) SQL Server shows an error:
Error converting data type nvarchar
to bigint
How can I fix this problem?
You could try to use ISNUMERIC to determine those rows that are indeed numeric:
UPDATE dbo.YourTable
SET BigIntColumn = CAST(NVarcharColumn AS BIGINT)
WHERE ISNUMERIC(NVarcharColumn) = 1
That would convert those rows that can be converted - the others need to be dealt with manually.
You should convert bigint to nvarchar not vice versa
cast(Other_Column_name as nvarchar) not cast (Column_Name as bigint)
you can try this:
CAST(CAST(col1 as NUMERIC) as BIGINT)
Here I convert navrchar value of column into bigInt and than perform Addition of thos two columns find blow :
SELECT (CAST(col1 AS BIGINT) + CAST(col2 AS BIGINT)) AS TotalValue from tableName

How to convert (cast) int to ntext

I need to convert int field like 1005 to ntext alike Alarm1005, but CAST(ID as ntext) doesn't work, so how can I convert(cast) int to ntext ?
CAST(CAST(ID as nvarchar(10)) as ntext)?
EDIT
As gbn has justly hinted, nvarchar(max) is actually a much more preferable type for storing large string data.
Two reasons:
You have plenty of functions that work with nvarchar as compared to those that can handle ntext.
The types ntext, text and image are officially deprecated.
And one other tiny reason is, you wouldn't have to double cast. It would be as simple as CAST(ID AS nvarchar(10)) or CAST(ID AS nvarchar(max)).
ALTER TABLE MyTable ADD new_column NTEXT
UPDATE MyTable SET new_column = cast(old_column as nvarchar(16))
ALTER TABLE MyTable DROP COLUMN old_column