Subtract Operator in Stored Proc for Concatenate - sql-server

I am getting the data type error in my stored procedure because I'm using Field1+'-'+Field2. I tried a convert and a cast, but it's not liking the syntax I used for that pesky -.
For the subtraction operation, what's the best way to use it as a hyphen or dash instead of an operator?
Thank you!!!

You need to convert both field to strings, like this:
Convert(VarChar(10), Field1) + '-' + Convert(VarChar(10), Field2)
If either field is a number, sql server will treat this as a math operation instead of concatenation.
** I used varchar(10) as an example. You should double check your data types and adjust the 10 accordingly.

If you are on 2012+
CONCAT(Field1,'-',Field2)
is a bit less verbose. Docs
All arguments are implicitly converted to string types and then
concatenated. Null values are implicitly converted to an empty string

Related

SQL Server string comparison with equals sign and equals or greater in the strings [duplicate]

I have seen prefix N in some insert T-SQL queries. Many people have used N before inserting the value in a table.
I searched, but I was not able to understand what is the purpose of including the N before inserting any strings into the table.
INSERT INTO Personnel.Employees
VALUES(N'29730', N'Philippe', N'Horsford', 20.05, 1),
What purpose does this 'N' prefix serve, and when should it be used?
It's declaring the string as nvarchar data type, rather than varchar
You may have seen Transact-SQL code that passes strings around using
an N prefix. This denotes that the subsequent string is in Unicode
(the N actually stands for National language character set). Which
means that you are passing an NCHAR, NVARCHAR or NTEXT value, as
opposed to CHAR, VARCHAR or TEXT.
To quote from Microsoft:
Prefix Unicode character string constants with the letter N. Without
the N prefix, the string is converted to the default code page of the
database. This default code page may not recognize certain characters.
If you want to know the difference between these two data types, see this SO post:
What is the difference between varchar and nvarchar?
Let me tell you an annoying thing that happened with the N' prefix - I wasn't able to fix it for two days.
My database collation is SQL_Latin1_General_CP1_CI_AS.
It has a table with a column called MyCol1. It is an Nvarchar
This query fails to match Exact Value That Exists.
SELECT TOP 1 * FROM myTable1 WHERE MyCol1 = 'ESKİ'
// 0 result
using prefix N'' fixes it
SELECT TOP 1 * FROM myTable1 WHERE MyCol1 = N'ESKİ'
// 1 result - found!!!!
Why? Because latin1_general doesn't have big dotted İ that's why it fails I suppose.
1. Performance:
Assume your where clause is like this:
WHERE NAME='JON'
If the NAME column is of any type other than nvarchar or nchar, then you should not specify the N prefix. However, if the NAME column is of type nvarchar or nchar, then if you do not specify the N prefix, then 'JON' is treated as non-unicode. This means the data type of NAME column and string 'JON' are different and so SQL Server implicitly converts one operand’s type to the other. If the SQL Server converts the literal’s type
to the column’s type then there is no issue, but if it does the other way then performance will get hurt because the column's index (if available) wont be used.
2. Character set:
If the column is of type nvarchar or nchar, then always use the prefix N while specifying the character string in the WHERE criteria/UPDATE/INSERT clause. If you do not do this and one of the characters in your string is unicode (like international characters - example - ā) then it will fail or suffer data corruption.
Assuming the value is nvarchar type for that only we are using N''

unable to update nvarchar(50) having czech letters in it [duplicate]

I have seen prefix N in some insert T-SQL queries. Many people have used N before inserting the value in a table.
I searched, but I was not able to understand what is the purpose of including the N before inserting any strings into the table.
INSERT INTO Personnel.Employees
VALUES(N'29730', N'Philippe', N'Horsford', 20.05, 1),
What purpose does this 'N' prefix serve, and when should it be used?
It's declaring the string as nvarchar data type, rather than varchar
You may have seen Transact-SQL code that passes strings around using
an N prefix. This denotes that the subsequent string is in Unicode
(the N actually stands for National language character set). Which
means that you are passing an NCHAR, NVARCHAR or NTEXT value, as
opposed to CHAR, VARCHAR or TEXT.
To quote from Microsoft:
Prefix Unicode character string constants with the letter N. Without
the N prefix, the string is converted to the default code page of the
database. This default code page may not recognize certain characters.
If you want to know the difference between these two data types, see this SO post:
What is the difference between varchar and nvarchar?
Let me tell you an annoying thing that happened with the N' prefix - I wasn't able to fix it for two days.
My database collation is SQL_Latin1_General_CP1_CI_AS.
It has a table with a column called MyCol1. It is an Nvarchar
This query fails to match Exact Value That Exists.
SELECT TOP 1 * FROM myTable1 WHERE MyCol1 = 'ESKİ'
// 0 result
using prefix N'' fixes it
SELECT TOP 1 * FROM myTable1 WHERE MyCol1 = N'ESKİ'
// 1 result - found!!!!
Why? Because latin1_general doesn't have big dotted İ that's why it fails I suppose.
1. Performance:
Assume your where clause is like this:
WHERE NAME='JON'
If the NAME column is of any type other than nvarchar or nchar, then you should not specify the N prefix. However, if the NAME column is of type nvarchar or nchar, then if you do not specify the N prefix, then 'JON' is treated as non-unicode. This means the data type of NAME column and string 'JON' are different and so SQL Server implicitly converts one operand’s type to the other. If the SQL Server converts the literal’s type
to the column’s type then there is no issue, but if it does the other way then performance will get hurt because the column's index (if available) wont be used.
2. Character set:
If the column is of type nvarchar or nchar, then always use the prefix N while specifying the character string in the WHERE criteria/UPDATE/INSERT clause. If you do not do this and one of the characters in your string is unicode (like international characters - example - ā) then it will fail or suffer data corruption.
Assuming the value is nvarchar type for that only we are using N''

Error converting data type nvarchar to real

I need to subtract two nvarchar values and store the result in another column. I understand that first I need to convert nvarchar to numeric values, but I always get this error
Error converting data type nvarchar to real
Just to mention in varchar values are stored only numeric values but I can't seem to get this conversion right.
This looks like a SQL Server error. If so, use try_convert():
select try_convert(real, string_col)
This returns NULL instead of an error if there are conversion issues.
You can find the offending values using:
select string_col
from t
where try_convert(real, string_col) is null and
string_col is not null;
use a case statement. It should be something like (t-sql pseudo code inside a SELECT)
case when IsNumeric(column1) AND IsNumeric(column2)
then cast(column1 as decimal) - cast(column2 as decimal)
else NULL end as column3
This is a classical example of why you shouldn't mix types (nvarchar and decimal in this case), there are all sorts of shananigans - like ('abc' - 5) or (NULL - NULL) or ('five' - '3 '). If this works, it might be a good idea to look at the "NULL" results, as this might give you valuable insights as to what kind of garbage is being collected in your system.
You said that...
Just to mention in varchar values are stored only numeric values but I
can't seem to get this conversion right.
If that is absolutely true, then there's a very high probability that there are 1 or 2 trailing control characters (Tab, Carriage Return, Line Feed, whatever) in the items causing the errors.
Try converting the NVARCHAR values to the MONEY datatype first. It won't work for leading control characters but it will for trailing control characters. Obvioussly your original original value doesn't haven more than 4 decimal places, of course.

cast to NVARCHAR(MAX) causes "chinese"/UTF encoded characters

I am using code like this in my SELECT statement:
CAST(HASHBYTES(N'SHA1', Bla) AS NVARCHAR(MAX)) AS hashed_bla
and end-up with "chinese"/UTF encoded characters in the ssms grid but also in upstream apps. Is there a way to change this? Does this have to do with the collation? Thanks!
What you have is working as expected. Take the following example:
SELECT HASHBYTES('SHA1','B8187F0D-5DBA-4D43-95FC-CD5A009DB98C');
This returns the varbinary value 0xA04B9CB18A2DC4BC08B83FCCE48A0AF1A1390756. You are then converting that value to an nvarchar, so get a result like N'䮠놜ⶊ별레찿諤㦡嘇' (on my collation). For an varbinary each 4 characters represents a single character. So, for the above A04B is the first character (which is N'䮠').
It appears what you are after is an varchar representing a varbinary value (you don't need an nvarchar here, as there will be no unicode characters). To do so, you need to use CONVERT and a style code. For the example I gave above that would be:
SELECT CONVERT(varchar(100),HASHBYTES('SHA1','B8187F0D-5DBA-4D43-95FC-CD5A009DB98C'),1);
Which returns the varchar value '0xA04B9CB18A2DC4BC08B83FCCE48A0AF1A1390756'. If you don't want the '0x' at the start, use style code 2, rather than 1.

Evaluate logical expressions in string column SQL

I have a table containing columns id(int), logical expression(varchar) and result(bit). The logical expression is stored in a varchar which I need to evaluate and put the result into the result column. For example, the column could contain:
'1=1'
'2<3 AND 1^1=1'
'3>4 OR 4<2'
The result column should then contain
1
0
0
Currently I am using a cursor to navigate the rows and using dynamic sql to evaluate the expression.
"IF(" + #expression + ") SET #result = 1"
Is there a better, more efficient way to do this? I would ideally like to get rid of the cursor. Any ideas? Would this be better performed using an assembly?
I'd go with a CLR.
I posted a very similar answer here: Convert string with expression to decimal
infact, the above answer would work fine unmodified for (and any other simple expressions):
SELECT dbo.eval('1=1' )
SELECT dbo.eval('3>4 OR 4<2' )
However, it would fail for the one using the ^ (caret) operator - you would need to tweak the CLR to handle the bitwise XOR.
Some time ago, I wrote a user-defined function in SQL to give the decimal result of evaluating infix arithmetic expressions like 1+2+3+4/(5-2). The code is here. You could probably adapt it to work for your boolean expressions. It uses a table of integers called Sequence0_8000, which you can populate in any way you want.

Resources