How to cast varchar in varbinary? - sql

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)

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)

How to pass large string_replacement in SQL Replace function

I am attempting to replace a very large characters with a existing character in SQL, like the below
select REPLACE('main context', 'text', 'CharactersOver8000')
It would throw the following error
String or binary data would be truncated.
I try to cast the whole replace to nvarchar(max) but it does not work. Any suggestion? Currently its on SQL2012
What is the cause of this error message?
From the Docs Online
If string_expression is not of type varchar(max) or nvarchar(max), REPLACE truncates the return value at 8,000 bytes. To return values greater than 8,000 bytes, string_expression must be explicitly cast to a large-value data type.
What is the solution?
string_expression in your case is 'MainContext', so you need to cast it to VARCHAR(MAX) or NVARCHAR(MAX) datatypes as
select REPLACE(CAST('main context' AS VARCHAR(MAX), 'text', 'CharactersOver8000')
Casting inside the replace should work. I just tested this:
SELECT REPLACE(CAST('MainContext' AS varchar(max)), 'text', '{8005 character string}')
And it worked.

Convert nvarchar(max) to varbinary(max)

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.

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