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.
Related
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
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
I'm trying to convert a string to rows using T-SQL. I've found some people using XML for this but I'm running into troubles.
The original record:
A new line seperated string of data
New In Progress Left Message On Hold Researching Researching (2nd Level) Researching (3rd Level) Resolved Positive False Positive Security Respond
Using the following statement converts this string into XML:
select
cast('<i>'+REPLACE(convert(varchar(max), list_items), CHAR(13) + CHAR(10),'</i><i>')+'</i>' as xml)
from
field
where
column_name = 'state' and table_name = 'sv_inquiry'
XML string:
<i>Unassigned</i><i>Assigned</i><i>Transferred</i><i>Accepted</i><i>Closed</i><i>Reactivated</i>
Now I would like to convert every 'i' node into a separate row. I've constructed the query below, but I can't get it working in the way that it returns all the rows...
select x.i.value('i[1]', 'varchar(30)')
from (
select cast('<i>'+REPLACE(convert(varchar(max), list_items), CHAR(13) + CHAR(10),'</i><i>')+'</i>' as xml)
from field
where column_name='state' and table_name='sv_inquiry'
) x(i)
This will return
Unassigned
To be clear, when i change 'i[1]' into 'i[2]' it will return 'Assigned'. I've tried '.', this will return the whole string in a single record...
How about using the nodes method on an XML datatype.
declare #xml xml
set #xml = '<i>Unassigned</i><i>Assigned</i><i>Transferred</i><i>Accepted</i><i>Closed</i><i>Reactivated</i>'
select
t.c.value('.', 'nvarchar(100)') as [Word]
from
#xml.nodes('/i') as t(c)
You can split a string into rows without XML, see for example the fnSplitString function at SQL Server Central.
Here's an example using the nodes() function of the xml type. I'm using a space as the delimiter because SQL Fiddle doesn't play well with line feeds:
select node_column.value('.', 'varchar(max)')
from (
select cast('<i>' + replace(list_items, ' ', '</i><i>') +
'</i>' as xml) xml_value
from field
) f
cross apply
xml_value.nodes('/i') node_table(node_column);
Live example at SQL Fiddle.
This question already has answers here:
How to concatenate text from multiple rows into a single text string in SQL Server
(47 answers)
Closed 7 years ago.
I have a sql function that includes this code:
DECLARE #CodeNameString varchar(100)
SELECT CodeName FROM AccountCodes ORDER BY Sort
I need to concatenate all results from the select query into CodeNameString.
Obviously a FOREACH loop in C# code would do this, but how do I do it in SQL?
If you're on SQL Server 2005 or up, you can use this FOR XML PATH & STUFF trick:
DECLARE #CodeNameString varchar(100)
SELECT
#CodeNameString = STUFF( (SELECT ',' + CodeName
FROM dbo.AccountCodes
ORDER BY Sort
FOR XML PATH('')),
1, 1, '')
The FOR XML PATH('') basically concatenates your strings together into one, long XML result (something like ,code1,code2,code3 etc.) and the STUFF puts a "nothing" character at the first character, e.g. wipes out the "superfluous" first comma, to give you the result you're probably looking for.
UPDATE: OK - I understand the comments - if your text in the database table already contains characters like <, > or &, then my current solution will in fact encode those into <, >, and &.
If you have a problem with that XML encoding - then yes, you must look at the solution proposed by #KM which works for those characters, too. One word of warning from me: this approach is a lot more resource and processing intensive - just so you know.
DECLARE #CodeNameString varchar(max)
SET #CodeNameString=''
SELECT #CodeNameString=#CodeNameString+CodeName FROM AccountCodes ORDER BY Sort
SELECT #CodeNameString
#AlexanderMP's answer is correct, but you can also consider handling nulls with coalesce:
declare #CodeNameString nvarchar(max)
set #CodeNameString = null
SELECT #CodeNameString = Coalesce(#CodeNameString + ', ', '') + cast(CodeName as varchar) from AccountCodes
select #CodeNameString
For SQL Server 2005 and above use Coalesce for nulls and I am using Cast or Convert if there are numeric values -
declare #CodeNameString nvarchar(max)
select #CodeNameString = COALESCE(#CodeNameString + ',', '') + Cast(CodeName as varchar) from AccountCodes ORDER BY Sort
select #CodeNameString
from msdn Do not use a variable in a SELECT statement to concatenate values (that is, to compute aggregate values). Unexpected query results may occur. This is because all expressions in the SELECT list (including assignments) are not guaranteed to be executed exactly once for each output row
The above seems to say that concatenation as done above is not valid as the assignment might be done more times than there are rows returned by the select
Here is another real life example that works fine at least with 2008 release (and later).
This is the original query which uses simple max() to get at least one of the values:
SELECT option_name, Field_M3_name, max(Option_value) AS "Option value", max(Sorting) AS "Sorted"
FROM Value_list group by Option_name, Field_M3_name
ORDER BY option_name, Field_M3_name
Improved version, where the main improvement is that we show all values comma separated:
SELECT from1.keys, from1.option_name, from1.Field_M3_name,
Stuff((SELECT DISTINCT ', ' + [Option_value] FROM Value_list from2
WHERE COALESCE(from2.Option_name,'') + '|' + COALESCE(from2.Field_M3_name,'') = from1.keys FOR XML PATH(''),TYPE)
.value('text()[1]','nvarchar(max)'),1,2,N'') AS "Option values",
Stuff((SELECT DISTINCT ', ' + CAST([Sorting] AS VARCHAR) FROM Value_list from2
WHERE COALESCE(from2.Option_name,'') + '|' + COALESCE(from2.Field_M3_name,'') = from1.keys FOR XML PATH(''),TYPE)
.value('text()[1]','nvarchar(max)'),1,2,N'') AS "Sorting"
FROM ((SELECT DISTINCT COALESCE(Option_name,'') + '|' + COALESCE(Field_M3_name,'') AS keys, Option_name, Field_M3_name FROM Value_list)
-- WHERE
) from1
ORDER BY keys
Note that we have solved all possible NULL case issues that I can think of and also we fixed an error that we got for numeric values (field Sorting).
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