SQL Server, Oracle8i syntax - sql

I am running the simple query below
select '''' + event_number + '''' +',' as Event_N
from mytable
which gives:
Event_N
---------------
'BAB0910000001',
'CDD0910000002',
'ODB0910000002',
'YDB0910000003',
'NYC0910000004',
Question 1: Is there a way in SQL that can show the result as:
Event_N
'BAB0910000001','CDD0910000002','ODB0910000002','YDB0910000003','NYC0910000004',
I could do a dirty step by pressing Delte and End but would not be efficient when more than 100 records.
I am using Aqua Data Studio 7.5.34 and the back end is MS SQL Server 2000/5/8.
Event_number data type is varchar.
Question 2: But when I tried to run this query, it showed me the error below. Could someone please help!!!
select '''' + event_key + '''' +',' as Event_K
from mytable
I am using Aqua Data Studio 7.5.34 and the back end is MS SQL Server 2000/5/8.
--event_key data type is int.
[Error] Script lines: 1-3 --------------------------
Conversion failed when converting the varchar value ''' to data type int.
Msg: 245, Level: 16, State: 1, Procedure: , Line: 1
I ran the following query, which gives:
select ''''||EVENT_KEY||'''' as Event_K
from mytable
EVENT_K
'28732033'
'28797708'
'28796943'
'28133100'
'28718239'
Question 3: Is there a way in SQL that could add a comma (,) to the end of these records and output the result similar to question 1?
I am using Aqua Data Studio 7.5.34 and the back end is oracle 8i

Question 1 and 3 - essentially the same as this question: Use SQL instead of Delete and End from keyboard
OMG Ponies' post includes links to a selection of techniques in Oracle, as well as SQLServer.
Question 2 requires an explicit CAST or CONVERT on the event_key, to change it into character instead of numeric data - like so:
select '''' + convert(varchar,event_key) + '''' +',' as Event_K
from mytable

Related

Incorrect syntax near 'JSON' - SQL Server 2014

I am trying to use it in my SQL Query exactly like it's shown in the link below on MSDN. The keyword JSON does not turn blue and gives error
Incorrect syntax near 'JSON'
What's wrong with it?
EDIT: I'm testing it for SQL Server 2014. The query is
SELECT * FROM food FOR JSON AUTO
FOR JSON AUTO is available from SQL SERVER 2016. If you are using SQL SERVER 2014 or former, then you can use the following approach:
SELECT '['+ STUFF((
SELECT ',{"Col1":"' + CAST(t1.name AS NVARCHAR(MAX)) + '",'+
+'"Col2":"'+CAST(t1.database_id AS NVARCHAR(MAX)) + '"}'
FROM Food t1 FOR XML PATH(''), TYPE
).value('.', 'varchar(max)'),1,1,''
) + ']';
You can validate the output using various online tools such as JSON LINT to make sure that the result is valid json-formatted result.
Update:
Here is the screenshot of the code and result:
Thank you Vahid for the query very handy. Just a quick modification if the record have '\' in their value JSON will fail so modified the query to accommodate that
SELECT '['+ STUFF((
SELECT ',{"Col1":"' + REPLACE(CAST(t1.name AS NVARCHAR(MAX)),'\','\\') + '",'+
+'"Col2":"' + REPLACE(CAST(t1.value AS NVARCHAR(MAX)),'\','\\') + '"}'
FROM Food t1 FOR XML PATH(''), TYPE
).value('.', 'varchar(max)'),1,1,''
) + ']';
JSON AUTO Only use in SQL Server 2016.

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 with subquery and concatenating variable using CRM on-premise data

I am working on a report where I need to provide a summary of notes for particular "activities/tasks".
Since the activity can accept multiple notes, I have to search for all the notes related to that activity. I then order it by date (new to old), and concatenate them with some other strings as such:
[Tom Smith wrote on 9/23/2016 1:21 pm] Client was out of office, left message. [Jane Doe wrote on 9/21/2016 3:24 pm] Client called asking about pricing.
The data comes from replicated tables of our on-premise CRM system, and I'm using SQL Server 2012. The tables I'm using are: AnnotationBase (contains the notes), ActivityPointerBase (contains the activities/tasks), and SystemUserID (to lookup usernames). Due to Data mismatch, I have to do some converting of the data types so that I can concatenate them properly, so that's why there's a lot of CAST and CONVERT. In addition, not all Activities have a NoteText associated with them, and sometimes the NoteText field is NULL, so I have to catch and filter the NULLs out (or it'll break my concatenated string).
I have written the following query:
DECLARE #Notes VarChar(Max)
SELECT
( SELECT TOP 5 #Notes = COALESCE(#Notes+ ', ', '') + '[' + CONVERT(varchar(max), ISNULL(sUB.FullName, 'N/A')) + ' wrote on ' + CONVERT(varchar(10), CAST(Anno.ModifiedOn AS DATE), 101) + RIGHT(CONVERT(varchar(32),Anno.ModifiedOn,100),8) + '] ' + CONVERT(varchar(max), ISNULL(Anno.NoteText, '')) --+ CONVERT(varchar(max), CAST(ModifiedOn AS varchar(max)), 101)--+ CAST(ModifiedOn AS varchar(max))
FROM [CRM_rsd].[dbo].[AnnotationBase] AS Anno
LEFT OUTER JOIN [CRM_rsd].[dbo].[systemUserBase] AS sUB
ON Anno.ModifiedBy = sUB.SystemUserId
WHERE Anno.ObjectId = Task.ActivityId--'0B48AB28-C08F-419A-8D98-9916BDFFDE4C'
ORDER BY Anno.ModifiedOn DESC
SELECT LEFT(#Notes,LEN(#Notes)-1)
) AS Notes
,Task.*
FROM [CRM_rsd].[dbo].[ActivityPointerBase] AS Task
WHERE Task.Subject LIKE '%Project On Hold%'
I know the above method is probably not very efficient, but the list of "Projects On Hold" is rather small (less than 500), so performance isn't a priority. What is a priority is to be able to get a consolidated and concatenated list of notes for each activity. I have been searching all over the internet for a solution, and I have tried many different methods. But I get the following errors:
Msg 102, Level 15, State 1, Line 3
Incorrect syntax near '='.
Msg 102, Level 15, State 1, Line 10
Incorrect syntax near ')'.
I envision two possible solutions to my problem:
My subquery errors are fixed or
Create a "view" of just the concatenated NotesText, grouped by ActivityId (which would work as a key), and then just query from that.
Yet even though I'm pretty sure my ideas would work, I can't seem to figure out how to concatenate a column and group at the same time.
What you are trying to do is display the records from one table (in your case ActivityPointerBase) and inside you want to add a calculated column with information from multiple records from another table (in your case AnnotationBase) merged in the rows.
There are multiple ways how you could achieve this that are different in terms of performance impact:
Option 1. You could write a scalar function that would receive as parameter the id of the task and would inside select the top 5 records, concatenating them in a procedural fashion and returning a varchar(max)
Option 2: You could use a subquery in combination with the FOR XML clause.
SELECT
SUBSTRING(
CAST(
(SELECT TOP 5 ', ' +
'[' + CONVERT(varchar(max), ISNULL(FullName, 'N/A')) +
' wrote on ' +
CONVERT(varchar(10), CAST(ModifiedOn AS DATE), 101) +
RIGHT(CONVERT(varchar(32),ModifiedOn,100),8) + '] ' +
CONVERT(varchar(max), ISNULL(NoteText, ''))
FROM [CRM_rsd].[dbo].[AnnotationBase] AS Anno
LEFT OUTER JOIN [CRM_rsd].[dbo].[systemUserBase] AS sUB ON Anno.ModifiedBy = sUB.SystemUserId
WHERE Anno.ObjectId = Task.ActivityId
ORDER BY Anno.ModifiedOn DESC
FOR XML PATH(''),TYPE
) AS VARCHAR(MAX)
),3,99999) AS Notes
,Task.*
FROM [CRM_rsd].[dbo].[ActivityPointerBase] AS Task
WHERE Task.Subject LIKE '%Project On Hold%'
What here happens is that by using the construct inside the CAST() we fetch the top 5 lines and make SQL server produce an XML with no element names, resulting in concatenation of the element values, we add comma as separator. Then we convert the XML to varchar(max) and remove the initial separator before the first record.
I prefer option 2, it will perform much better then using a scalar function.

Sql Server Split and Concatenation

I have data in the following format in a sql server database table
[CPOID] [ContractPO] [ContractPOTitle]
1 10-SUP-CN-CNP-0001 Drytech
2 10-SUP-CN-CNP-0002 EC&M
I need to write a stored procedure to generate the following result
[CPOID] [ContractPO] [ContractPOTitle] [ConcatField]
1 10-SUP-CN-CNP-0001 Drytech CNP-0001-Drytech
2 10-SUP-CN-CNP-0002 EC&M CNP-0002-EC&M
where [ConcatField] generate the result using split the last two values of the [ContractPOTitle] column and combine with the [ContractPOTitle]
If the ContractPO field is always the same length, you could just do:
SELECT
CPOID,
ContractPO,
ContractPOTitle,
RIGHT(ContractPO, 8) + '-' + ContractPOTitle as [ConcatField]
FROM MyTable
Assuming that the length of the ContractPO field is not fixed AND we have to rely on stripping out the text after the next to last '-', the following SQL will work. It's a bit ugly, but these types of operations are necessary because there doesn't appear to be a LASTINDEX function available out of the box in SQL Server.
SELECT
CPOID,
ContractPO,
ContractPOTitle,
RIGHT(ContractPO, CHARINDEX('-', REVERSE(ContractPO), CHARINDEX('-', REVERSE(ContractPO)) + 1) - 1) + '-' + ContractPOTitle as [ConcatField]
FROM #myTable