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

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)

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 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)

Convert a varchar(10) into an int in SQL Server 2014

Is it possible to convert a varchar(10) into an int in SQL Server 2014?
I tried the following code, but I get a conversion error
Declare #Random varchar(10)
set #Random = CONVERT(varchar, right(newid(),10))
Declare #rand int = cast(#Random as int)
select #rand
Is it possible to convert a varchar(10) into an int under SQL Server 2012?
Yes, if the varchar(10) string is all numeric characters and the string is within the bound of an int:
-2^31 (-2,147,483,648) to 2^31-1 (2,147,483,647)
In other words, this will work:
select cast('2147483647' as int)
This will not:
select cast('2147483648' as int)
I tried the following code, but I get a conversion error
The code in your question isn't testing whether you can convert a string to an integer, it is testing whether any random string can be converted. Your random strings contain alpha characters that cannot convert to an integer so you are getting conversion errors. But even if you limit the random string to numbers, you will still only be able to convert numeric strings up to 2147483647 before you overflow your int. I don't think that generating (not-so) random strings that meet this criteria will prove much. The simple answer to your question is yes, you can convert a string to an int, as long as the string meets the requirements of an int.
You could try:
SELECT TRY_CAST(RIGHT(CAST(convert(VARBINARY, NEWID(), 1) AS BIGINT),10) AS INT);
Rextester Demo
Or if you use only 9 digitis:
SELECT RIGHT(CAST(convert(VARBINARY, NEWID(), 1) AS BIGINT),9) + 0;

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 implicit casting to VARCHAR(MAX)

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.