CONCAT function alternative in SQL Server 2008 - sql

I am trying to use CONCAT function in SQL Server 2008. It doesn't work because it is not available in that version:
$sql = "SELECT DISTINCT(CONCAT(Project, '-', FLOOR_ID)) AS value FROM dbo.IMP_MODEL_GEOMETRY WHERE Project LIKE '%".$test_term."%'";
When i was google "How to" I found a post here said using + instead. So I tried:
$sql = "SELECT DISTINCT( (Project + '-' + FLOOR_ID) ) AS value FROM dbo.IMP_MODEL_GEOMETRY WHERE Project LIKE '%".$test_term."%'";
But i got this message:
[Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Conversion failed when converting the nvarchar value ' 22067-' to data type int.
So, how should i solve this?

You are mixing datatypes for the + operation. In this case SQL server will attempt to convert VARCHAR expression to INT (this is done according to datatype precedence rules). You need to explicitly cast INT to VARCHAR:
SELECT COALESCE(Project, '')
+ '-'
+ COALESCE(CAST(FLOOR_ID AS VARCHAR(11)), '')
CONCAT function does not return NULL if the arguments are NULL. COALESCE(..., '') is required to match the behavior.

Try casting the FLOOR_ID to text:
SELECT DISTINCT
Project + '-' + CAST(FLOOR_ID AS VARCHAR(MAX)) AS value
FROM dbo.IMP_MODEL_GEOMETRY
WHERE Project LIKE '%".$test_term."%'";
The current error message mentions the string ' 22067-', which implies that the FLOOR_ID is the source of the problem.

Cast Project and FLOOR_ID to String like this -
CAST(Project AS VARCHAR("MAX LENGTH OF PROJECT FIELD"))
and same for FLOOR_ID

Related

[Informatica][ODBC 20101 driver][Microsoft SQL Server]Invalid operator for data type. Operator equals minus, type equals varchar

REPLACE(T.FirstName, ' ', '') + '.' +
REPLACE(REPLACE(T.LastName, ' ', ''), '''', '') + '.' + SUBSTRING(CONVERT(varchar(50), T1.Id), 1, 8) +
'#outlook.com' AS 'EmailAddress'
EmailAddress is the one of the column which has above logic. Informatica workflow failing due to conversion with below error. Can any one help me how to handle this.
Source is SQL Server, and target is Oracle
I get this error:
[Informatica][ODBC 20101 driver][Microsoft SQL Server]Invalid operator for data type. Operator equals minus, type equals varchar.
This is not Informatica error. This is an error thrown by MS SQL Server and passes on to Informatica.
This means, the error is thrown by the query. Debug the query on your source system. It seems it some part results in a minus that is then interpreted as substraction by the Query Optimizer.
{FN CONCAT( {FN CONCAT({FN CONCAT({FN CONCAT( {FN CONCAT(REPLACE(T.FirstName,' ',''), '.')}, REPLACE(REPLACE(
T.LastName,' ',''),'''',''))},'.' )}, SUBSTRING(convert(varchar(50),T1.PersonId),1,8))},'#Outlook.com')} AS 'EmailAddress'
Made the changes as above. SQL Server doesnt have any issue with '+' or 'CONCAT'. inforamtica was throwing error for '+' for concatenation in query. Now im able to load the data to Oracle table from SQL Server. Thanks all for the responses and help.

SQL Server SELECT To Return String Including Single Quotes

I need to get a formatted string with data from a SELECT statement. The problem is that I need it to return with single quotes. Here's an example.
I have a table that contains 2 columns TrainingSwipeID (int) and ExtendedDate (datetime). For an example I have a row in the table that contains
TrainingSwipeID = 123
TrainingEnd = 04/23/2019 09:00:00
I need to create a SELECT statement that will return the formatted string such as
{'TrainingSwipeID':123,'TrainingEnd ':04/23/2019 09:00:00}
I've researched and found that you can double single quote to get around this issue. I've tried the following with no luck and I get the following error "Conversion failed when converting the varchar value '{'TrainingSwipeID':' to data type int."
SELECT '{''TrainingSwipeID'':' + TrainingSwipeID + '''TrainingEnd'':' + TrainingEnd + '}'
AS MyFormattedString
FROM TrainingSwipe
Can anyone help?
The numeric and date/time data types have a higher precedence than the string data types. That's why you need to convert the numeric types into strings and prevent undesired implicit conversions.
SELECT '{''TrainingSwipeID'':' + CAST(TrainingSwipeID AS varchar(15))
+ '''TrainingEnd'':' + CONVERT( varchar(20), TrainingEnd , 101) + ' '
+ CONVERT( varchar(20), TrainingEnd , 8) + '}'
AS MyFormattedString
FROM TrainingSwipe
I finally used the simplest answer from #AlexKudryashev but Luis' answer worked as well.
SELECT CONCAT('{''TrainingSwipeID'':' , TrainingSwipeID, ',''TrainingEnd'':', TrainingEnd, '}')

System.FormatException: 24141: A number is expected at position 47 of the input. The input has )

I have a table in sqlserverdb which contains column name EntityType, EntityJson.In EntityJson column contains following json value,
{"EntityId":{"Type":"String","Value":"bf58bbc6-0a5a-b9e0-4fb6-5e55604a1b68"},"Name":{"Type":"string","Value":"GasAssets"},"TenantName":{"Type":"string","Value":"v2rdemo"},"TenantId":{"Type":"string","Value":"c091e548-b45a-49b4-b8ec-2cb5e27c7af6"},"EntityType":{"Type":"string","Value":"EntityAssets"},"CreatedBy":{"Type":"string","Value":""},"ModifiedBy":{"Type":"string","Value":""},"Created":{"Type":"string","Value":""},"Modified":{"Type":"string","Value":""},"Parent":{"Type":"string","Value":""},"LastChat":{"Type":"string","Value":""},"Latitude":{"Type":"string","Value":-33.3479019999504},"Longitude":{"Type":"string","Value":6.203906305532271}}
and EntityType column value is "EntityAssets".
On GeoServer I have written the following query
SELECT
geometry::STGeomFromText('POINT(' + CAST(JSON_VALUE(EntityJson, '$.Latitude.Value') As CHAR(20)) + ' ' + CAST(JSON_VALUE(EntityJson, '$.Longitude.Value') AS CHAR(20)) + ')', 4326) as geometria
FROM
dbo.Entities
where
EntityType = 'EntityAssets'
While previewing layer on click openlayer I'm getting same exception.
But Inside Microsoft Sql Server Mgmt Studio running it's working fine with where clause and if i remove where clause and Execute again Query without where clause getting same Exception on Sql Server Mgmt studio.
A number is expected at position 47 of the input. The input has ).
It's hard to be sure without seeing your data, but the error sounds like you have a row with no or empty Latitude.Value and Longitude.Value. You will get a very similar error by running this query:
SELECT
geometry::STGeomFromText('POINT(' + '' + ' ' + '' + ')', 4326) as geometria
FROM
dbo.Entities
This simulates your two CASTs returning empty strings.
See also this old question on MSDN.

Update Concat statement SQL Server 2008 [duplicate]

I was looking for a CONCAT function in SQL Server 2008 R2. I found the link for this function. But when I use this function, it gives the following error:
Msg 195, Level 15, State 10, Line 7
'CONCAT' is not a recognized built-in function name.
Does the CONCAT function exists in SQL Server 2008 R2?
If not, how do I concatenate strings in SQL Server 2008 R2?
Just for completeness - in SQL 2008 you would use the plus + operator to perform string concatenation.
Take a look at the MSDN reference with sample code. Starting with SQL 2012, you may wish to use the new CONCAT function.
CONCAT is new to SQL Server 2012. The link you gave makes this clear, it is not a function on Previous Versions, including 2008 R2.
That it is part of SQL Server 2012 can be seen in the document tree:
SQL Server 2012
Product Documentation
Books Online for SQL Server 2012
Database Engine
Transact-SQL Reference (Database Engine)
Built-in Functions (Transact-SQL)
String Functions (Transact-SQL)
EDIT Martin Smith helpfully points out that SQL Server provides an implementation of ODBC's CONCAT function.
I suggest you cast all columns before you concat them
cast('data1' as varchar) + cast('data2' as varchar) + cast('data3' as varchar)
This should work for you.
CONCAT, as stated, is not supported prior to SQL Server 2012. However you can concatenate simply using the + operator as suggested. But beware, this operator will throw an error if the first operand is a number since it thinks will be adding and not concatenating. To resolve this issue just add '' in front. For example
someNumber + 'someString' + .... + lastVariableToConcatenate
will raise an error BUT '' + someNumber + 'someString' + ...... will work just fine.
Also, if there are two numbers to be concatenated make sure you add a '' between them, like so
.... + someNumber + '' + someOtherNumber + .....
NULL safe drop in replacement approximations for SQL Server 2012 CONCAT function
SQL Server 2012:
SELECT CONCAT(data1, data2)
PRE SQL 2012 (Two Solutions):
SELECT {fn CONCAT(ISNULL(data1, ''), ISNULL(data2, ''))}
SELECT ISNULL(CAST(data1 AS varchar(MAX)), '') + ISNULL(CAST(data2 AS varchar(MAX)), '')
These two solutions collate several excellent answers and caveats raised by other posters including #Martin Smith, #Svish and #vasin1987.
These options add NULL to '' (empty string) casting for safe NULL handling while accounting for the varying behaviour of the + operator pertaining to specific operands.
Note the ODBC Scaler Function solution is limited to 2 arguments whereas the + operator approach is scalable to many arguments as needed.
Note also the potential issue identified by #Swifty regarding the default varchar size here remedied by varchar(MAX).
(city + ', ' + state + ' ' + zip) as ctstzip for select
(city + ', ' + state + ' ' + zip) for insert
Only cast or convert if any field type is different from others.
On insert the value needs to be in the correct spot you need it be inserted. Using "as" will give you an error.
i.e.
Insert into testtable (ctstzip) Values ((city + ', ' + state + ' ' + zip))
Yes the function is not in sql 2008. You can use the cast operation to do that.
For example we have employee table and you want name with applydate.
so you can use
Select cast(name as varchar) + cast(applydate as varchar) from employee
It will work where concat function is not working.
You can use '+' between the strings that you want to concat like
SELECT string1 + string2
If one of those give conversion error like if one of the columns is an int column you should cast it before concatenating the columns like
SELECT (CONVERT(nvarchar, intColumn) + string2

SQL query combine two columns that contain different data type

I need to retrive data from two columns one has char and the other is integer. I use the following:
SELECT CONCAT(REQ.RQ_USER , _REQ_RQ_VC) AS 'MSR ID / Version'
from REQ
WHERE rq_type_id = '107'
I get syntax error. Is there any way to work around this problem?
Use CONVERT function to convert integer to string. your final query should be as follows :
SELECT CONCAT( CONVERT(varchar(10), REQ.RQ_USER) , _REQ_RQ_VC) AS 'MSR ID / Version'
FROM REQ
WHERE rq_type_id = '107'
You can find more details about CONVERT function on the following link : CONVERT (Transact-SQL)
Finally I figured out how to solve the issue by implementing the following syntax:
Select '[' + CAST (REQ.RQ_USER_TEMPlATE_06 AS VARCHAR(5000)) + ']' + req.rq_req_id AS 'MSR ID / Version' FROM REQ WHERE rq_type_id = '107'