SQL_Noob
SQL_Noob

Reputation: 1291

Subtract Operator in Stored Proc for Concatenate

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

Upvotes: 0

Views: 1127

Answers (2)

Martin Smith
Martin Smith

Reputation: 453543

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

Upvotes: 0

George Mastros
George Mastros

Reputation: 24498

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.

Upvotes: 2

Related Questions