How can I get a SQL query result in CSV format? - sql

I have an SQL query that returns some rows. How can I change it so that the output of the query is in CSV format?
I have found a way to make the result in XML format, but because of the nature of XML the result is too large to be useful.
The query is very large (and it's not really important), so I wont post it here. Here is a link to it.Link
I don't want the SQL query to save the result as a CSV file.

YES
try this
DECLARE #query nvarchar(max)
select #query = STUFF( (SELECT N',' + cast( id as nvarchar)
from TableX
--some WHERE clause here as well
FOR XML PATH(''), TYPE ).value('.', 'NVARCHAR(MAX)') ,1,1,'')
select #query
NO variable :
select STUFF( (SELECT N',' + cast( id as nvarchar)
from TableX
FOR XML PATH(''), TYPE ).value('.', 'NVARCHAR(MAX)') ,1,1,'')

Like this:
select field1
, '","'
, field2
, '","'
etc

Related

How to Count attendance hours on each day by user on SQL Server

I am new here.
I have the fallowing data on a table:
And I need to get the fallowing result:
I am using the fallowing SQL query:
SQL Query
DECLARE #sql AS NVARCHAR(MAX)=''
DECLARE #cols AS NVARCHAR(MAX)=''
select #cols = STUFF((SELECT distinct ',' + QUOTENAME(Date)
FROM vRecords
ORDER BY ',' + QUOTENAME(Date)
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
SET #sql = N'
SELECT EmpID, Name, ' + #cols + '
FROM (
select EmpID,Name,Date,Time
from vRecords
) a
PIVOT(COUNT(Time) FOR Date IN (' + #cols + ')) p'
EXECUTE(#sql)
What I need to accomplish is to know how many TIMES the user have a record on each DATE
But I am getting wrong result:
What am I doing wrong?
Sorry for all the links but because I am new I can't embed images.
I figured the issue.
All the problem was related to date format.
The columns were been generated with this format 2018-09-12 and the data was on this format 12/09/2018.
Any way, thanks for the comments.

More than VARCHAR(MAX) values in SQL Server

I have some tables with more than 700 columns/1000 columns.
Now I want to display all columns from this table to ISNULL(col1,0) format because when I use PIVOT/UNPIVOT and if there are some NULL values then they wont be converted to NULL and becomes empty strings. So I am trying to replace those NULLs with 0.
In this example I used sysobjects table so that you can try it in your ssms.
The result of this is incomplete as neither VARCHAR(MAX) nor NVARCHAR(MAX) is enough. How do I get all rows rather than few rows here?
DECLARE #colsUnpivot VARCHAR(MAX)
SET #colsUnPivot = STUFF((
SELECT ',' + 'ISNULL(' + QUOTENAME(name) + ', 0) AS '
+ QUOTENAME(name)
FROM sysobjects t
FOR XML PATH(''), TYPE ).value('.', 'NVARCHAR(MAX)') ,1,1,'')
PRINT #colsUnPivot
set #query = 'SELECT id,code_name,lkp_value
FROM
(
SELECT unitid,institution,city,state,zip, '+ #colsUnpivot+'
FROM sysobjects) AS cp
UNPIVOT (lkp_value for code_name IN ('+#colsUnPivot+')
) AS up'
--PRINT #Query
--PRINT #Query1
exec(#query)
I mean the code above does not make sense but I can not produce same thing that I have as i have to use sysobjects here.
But above code is throwing an error:
Msg 102, Level 15, State 1, Line 6
Incorrect syntax near '('.
And that's because there is so much data and it's being truncated.
Here is what my PRINT says,
,ISNULL([opd_
So I still think its truncating.
Your problem is that the PRINT command will truncate the data for display in SSMS.
I would suggest leaving it as XML and doing a SELECT, if you just need to see the data in SSMS without truncating:
DECLARE #colsUnpivot xml
SET #colsUnPivot = (SELECT ',' + 'ISNULL(' + QUOTENAME(name) + ', 0) AS '
+ QUOTENAME(name)
FROM sysobjects t
FOR XML PATH(''), TYPE ).value('.', 'NVARCHAR(MAX)')
SELECT #colsUnPivot
SSMS treats XML output differently and has a higher threshold for truncating the data.
Use SELECT instead of print in your SQL.
SELECT #colsUnPivot
Also, make sure that these values are maxed out in Results to Grid:

MS SQL:Pivot Table order columns

I'm hoping some can help clarify what I should be doing. I'm essentially reading in a Table with dates and then Im trying to convert these dates into individual columns.
Unfortunately the columns come out out of order. How do I order these columns into |01/01/2013|02/01/2013| etc? Any guidance would be much appreciated.
DECLARE #cols AS NVARCHAR(MAX),
#query AS NVARCHAR(MAX);
SET #cols = STUFF((SELECT distinct ',' + QUOTENAME(c.GL_Effective_Date)
FROM [03_rdm].[Table_2013] c
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set #query = 'SELECT Ref_Account_Class, ' + #cols + ' from
(
select TOP 100 PERCENT
Ref_Account_Class
, GL_Amount
, GL_Effective_Date
from [03_rdm].[Table_2013]
where Ref_Account_Class = ''Accounts Receivable''
order by GL_Effective_Date
) x
pivot
(
max(GL_Amount)
for GL_Effective_Date in (' + #cols + ')
) p '
execute(#query)
You need to order in this statement:
SET #cols = STUFF((SELECT distinct ',' + QUOTENAME(c.GL_Effective_Date)
FROM [03_rdm].[Table_2013] c
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
When using distinct though, you can only order by items in the select list, so you can't order by c.GL_Effective_Date, it would need to be the full statement (',' + QUOTENAME(c.GL_Effective_Date), but since QUOTENAME implicitly converts your date to a VARCHAR these will not come out in order. So instead of DISTINCT you can use GROUP BY to remove duplicates:
SET #cols = STUFF((SELECT ',' + QUOTENAME(c.GL_Effective_Date)
FROM [03_rdm].[Table_2013] c
GROUP BY c.GL_Effective_Date
ORDER BY c.GL_Effective_Date
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
Which should give the ordering you require. This should also be marginally more efficient, although probably not noticably. When you use a scalar function with distinct the function is applied to all rows, then duplicates removed from the results, however with group by, first duplicates are removed, then the function is applied to the results. As mentioned, this will not be noticable with QUOTENAME, but be a useful bit of knowledge to have for future reference.
Instead of using distinct, use group by:
SET #cols = STUFF((SELECT ',' + QUOTENAME(c.GL_Effective_Date)
FROM [03_rdm].[Table_2013] c
GROUP BY c.GL_Effective_Date
ORDER BY c.GL_Effective_Date
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)'),
1, 1, '');

Dynamic Query Restructuring for View

I have created a dynamic SQL query that I want to use as a view, however, the query is dependent on using 'DECLARE' statements. I have tried unsuccessfully to restructure it without the 'DECLARE' statements, but can't quite get it right. I am using SQL Server Express 2014 and would appreciate any and all help.
DECLARE #query nvarchar(MAX)
DECLARE #Name nvarchar(MAX)
select #Name = STUFF((SELECT distinct ',' + QUOTENAME(Name)
FROM [dbo].[ObjectView]
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
SET #query = ' SELECT * from
(
select *
from [dbo].[ObjectView]
)t
pivot (MAX(Value) for Name IN (' +#Name+ ')) AS PivotTable'
execute(#query)
You may have to play with the XML syntax. I'm pretty rusty.
create view viewname as
select * --< you really should call out the fields, here...
from(
select * --< ...and here.
from ObjectView
t
pivot( MAX( Value ) for Name in(
select distinct QUOTENAME( Name )
FROM ObjectView
FOR XML PATH )
) AS PivotTable

SQL Server Rows to Columns using subquery

I tried to get rows into column using comma delimeted using this but how to achieve this using subquery, I achived that in oracle.
SQL Server :
DECLARE #listStr VARCHAR(MAX)
SELECT #listStr = COALESCE(#listStr+',' ,'') + email
FROM RDT_USER
SELECT #listStr
Oracle :
SELECT RTRIM(XMLAGG(XMLELEMENT(E, EMAIL || ',')).EXTRACT('//text()'), ',') AS RECEIVERID
FROM (SELECT DISTINCT (EMAIL) AS EMAIL
FROM RDT_USER
)
OUTPUT Expected :
j1#gmail.com,j2#gmail.com,j3#gmail.com,j4#gmail.com
You can use this:
DECLARE #listStr VARCHAR(MAX) =
STUFF(
(
SELECT DISTINCT ',' + email
FROM RDT_USER
FOR XML PATH(''), TYPE
).value('.', 'VARCHAR(MAX)')
,1,1,'')
SELECT #listStr
If you just want to select without variables, this should work:
SELECT
STUFF(
(
SELECT DISTINCT ',' + email
FROM RDT_USER
FOR XML PATH(''), TYPE
).value('.', 'VARCHAR(MAX)')
,1,1,'')