SQL Server implicit casting to VARCHAR(MAX) - sql

I have a SQL function with following signature
(
#value as VARCHAR(MAX)
)
RETURNS NCHAR(47)
What will happen if the input of the function will be int?
Implicit casting to VARCHAR(MAX)?
i.e if the input is int 12 how will it be transferred to the function input leading zeros and 12 - "000000..000012"

It gets cast to varchar but there will be no leading 0's, it will simply be read as 12. Just because you specify varchar(max) doesn't mean it will use the space it has and automatically fill it with 0's.

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)

Nvarchar working with logical operator working?

Just need your help here.
I have a table T
A (nvarchar) B()
--------------------------
'abcd'
'xyzxcz'
B should output length of entries in A for which I did
UPDATE T
SET B = LEN(A) -- I know LEN function returns int
But when I checked out the datatype of B using sp_help T, it showed column B as nvarchar.
What's going on ?
select A
from T
where B > 100
also returned correct output?
Why is nvarchar working with logical operators ?
Please help.
Check https://learn.microsoft.com/en-us/sql/t-sql/data-types/data-type-conversion-database-engine?view=sql-server-2017 where it is said that data types are converted explicitly or implicitly when you move, compare or store a variable. In your case, you are comparing column B with 100, forcing sql server to implicitly convert it to integer type (check the picture about conversions on the same page). As a prove, try to alter a row putting some text in column B and, after repeating your select query B>100, sql server will throw a conversione error trying to obtain an integer out of your text.
It works because of implicit conversion between types.
Data type precedence
When an operator combines expressions of different data types, the data type with the lower precedence is first converted to the data type with the higher precedence. If the conversion isn't a supported implicit conversion, an error is returned.
Types precedence:
16. int
...
25. nvarchar (including nvarchar(max) )
In you example:
select A
from T
where B > 100
--nvarchar and int (B is implicitly casted to INT)
when adding a column to a table in ssms, not adding a datatype a "default" datatype is chosen. for me on 2017 developer it's nchar(10). if you want it to be int define the column with datatype of int. in tsql it'd be
create table T (
A nvarchar --for me the nvarchar without a size gives an nvarchar(2)
,B int
);
sp_help T
--to make a specific size, largest for nvarchar is 4000 or max...max is the replacement for ntext of old, as.
create table Tmax (
A nvarchar(max)
,B int
);
--understanding nvarchar and varchar for len() and datalength()
select
datalength(N'wibble') datalength_nvarchar -- nvarchar is unicode and uses 2 bytes per char, so 12
,datalength('wibble') datalength_varchar -- varchar uses 1 byte per so 6
,len(N'wibble') len_nvarchar -- count of chars, so 6
,len('wibble') len_varchar -- count of char so still 6
nvarchar(max) and varchar(max)
hope this helps, the question is a bit discombobulated

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

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)

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.

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)