Generating CSv through a query in sql - sql

I have created a database, a table, and entries in that table through basic SELECT and INSERT INTO commands.
To view the entries I am using the basic query:
USE test1
SELECT * FROM orders
where test1 is Database and orders is Table name.
I can see the entries.
How can I store the results to a CSV?
With the query
SELECT * FROM orders
INTO OUTFILE '/path/to/file.csv'
FIELDS ESCAPED BY '""'
TERMINATED BY ',' ENCLOSED BY '"'
LINES TERMINATED BY '\n'"
I am getting an error
Msg 156, Level 15, State 1, Line 4
Incorrect syntax near the keyword 'INTO'.

You do have the option to output to csv from within management studio, you can return your grid as normal then right click and click "Save results As..."
or
Using SQLMD as per question How to export SQL Server 2005 query to CSV
sqlcmd -q "select col1,col2,col3 from table" -oc:\myfile.csv -h-1 -s","
Alternative is create it into a variable and then save that via your application e.g.
declare #csv varchar(max) = ""
select #csv += replace(column1, ',','","') + ', ' + replace(column1, ',','","') + char(13) + char(10) from orders
select #csv csv
Regards
Liam

If you're not as familiar with SQL and would like a more graphical based approach, you could always use the Import/Export Wizard. Little more user-friendly to people who may be new to SQL.

Related

SQL Server: removing line breaks when exporting data to csv file using Bulk export utility

I have a table which I need to export to a csv file. This table has an xml field which can have line breaks that I must remove.
I am using the bcp utility to export data from Sql Server to the csv file.
This is the strucutre of the table:
ID int
CODE varchar(20)
XML_DATA xml
This is the command I am using:
bcp "SELECT ID, CODE, replace(convert(nvarchar(max), XML_DATA), CHAR(13)+CHAR(10), ' ') as XML_DATA FROM MYDB.dbo.MyTable" queryout C:\output.csv -c -t0x1F -T -S "10.10.10.28"
For some reasons the output file still contains the line breaks. But if I run the same query on SQL Server for a record which has a line break, the output is correct (line breaks removed):
SELECT
ID,
CODE,
replace(convert(nvarchar(max), XML_DATA), CHAR(13)+CHAR(10), ' ') as XML_DATA
FROM MYDB.dbo.MyTable
WHERE ID = 1099; -- record with a line break in the XML_DATA field
What am I missing here?
Solved replacing this line
replace(convert(nvarchar(max), XML_DATA), CHAR(13)+CHAR(10), ' ') as XML_DATA
with this
replace(replace(convert(nvarchar(max), XML_DATA), CHAR(13), ' '), CHAR(10), ' ') as XML_DATA
Also I would like to point out that Sql Server Management Studio by default does not include CLRF characters on copy/paste from a query result, you must explicitly enable an option to preserve CLRF characters and restart SQL Server: preverse CLRF on Sql Server Management Studio query result. That was giving me some confusion ^_^

How to create a script to create a table

I am using SQL Server Management Studio 2017. I'm having a table in my local machine. Let's say its name is Email. Inside the Email table, there is a column name Language and its value can be 'en' or 'zh'. Beside this Language column, there are some more columns.
Now my colleague also has the same table but different machine and he only has the rows where Language is en. He doesn't have the rows where Language is zh yet.
How can I use this software to generate a SQL script to insert data to his table but with rows only where Language = 'zh' so that both table will be the same.
To be more clear , I need to send him the INSERT script with also contains the values of the data, so that he can use to INSERT to his database in his local machine.
Or is it any way else?
Is this what you want?
insert into colleague.dbo.email ( . . . )
select . . .
from my.dbo.email
where language = 'zh';
There are a couple of ways - the first is quick and requires no code, but you need to manually get rid of the rows you don't want yourself, the other is more flexible but you have to code it. There are also third party tools you can get to do this for you.
If you just want to do this once, you can do the following (this is from a different version of SSMS, but it should be similar)
right click on the database, select tasks, select generate scripts. Then pick the table you want, go next, then in the advanced settings find the "types of data to script" and change it to data. This should generate a script to load all the data from your table - you would need to edit it to just load the rows you want.
Another option is to write a script that basically makes the data you want yourself. You would need set it up to start with, and adjust it if you ever change the table format, but you can edit the selection script so that it only gets the data you want. I'm sure you could write a script that would create this automatically for you, but I've never needed one, so I haven't thought about it.
Something like this one
With baseRows as
(
--This bit gets the data you want
Select E.*
, ROW_NUMBER() over(ORDER BY ID) as RowNo
From dbo.Email E
Where E.Language = 'zh' -- whatever selection you need here
)
, selectRows as
(
--This bit creates the data select statments to set the data to import
Select
case when BR.RowNo = 1 then '' else 'Union All ' end
+ 'Select '
+ convert(varchar(10), BR.userID) + ' as userID, ' -- required integer example
+ case when BR.backupID is null then 'NULL' else CONVERT(varchar(10), BR.backupID) end + ' as backupID, ' -- nullable integer example
+ '''' + BR.Name + ''' as name, ' -- required nvarchar example
+ case when BR.groupname IS null then 'NULL' else '''' + BR.groupname + '''' end + ' as groupname, ' --nullable varchar example
+ CONVERT(varchar(2), BR.isActive) + ' as isActive, ' --bit example
as SQL
from baseRows BR
)
Select
--This creates the insert command row (top row) of the final query
'Insert into Email (
userID
, backupID
, name
, groupName
, IsActive
)' as SQL
UNION ALL
Select SQL from baseRows --and adds the data to the following rows
If you run this script, the output would be the script you are looking for to load the data into another machine.
RightClick on Database name(table in which Database)--->Tasks--->Generate Scripts--->Next--->select specific database objects--->select Table--->Save to file = ADVANCED--->click on Advanced--->types of data to script = "Data Only"--->Give the path(where to store theinsert commands)

Insert multiline in varchar

Is it possible to save a multiline varchar in SQL Server?
DECLARE #SQL VARCHAR(256)
SELECT #SQL = 'SELECT
ID, Name
FROM
Cust'
INSERT INTO
MultiLineTBL (SQL)
VALUES
(#SQL)
So this query:
SELECT SQL From MultiLineTBL
will return:
SELECT
ID, Name
FROM
Cust
Not the straight line:
SELECT ID, NAME FROM Cust
How is it possible to store a multiline varchar?
Your sql query have syntex error:
DECLARE #SQL VARCHAR(256) ;
--please update query like that
set #SQL = 'insert into MultiLineTBL(col1,col2)
SELECT ID, Name FROM Cust';
--and execure like that:
exec(#SQL);
Yes, it is possible to store a multi-line varchar in a table. In fact, the value in your example is stored correctly.
As AlexK has correctly commented, multi-line values are not displayed correctly in SQL Server Management Studio when it is configured to return the results in a grid, and that (viewing the results in a grid) must be what gave you the wrong impression. As per my observation, SSMS replaces every control character, including CR (CHAR(13)) and LF (CHAR(10)), with a space in this display mode.
Try switching to Results to Text (Ctrl+T) before running the query and you will see that line delimiters are actually preserved.

How can I avoid the ',' using OPENROWSET or BULK INSERTION?

I have to read and insert into a table i already have in sql server 2005 i have to read a txt file that has more than 1million of records, it worked great using this method:
set #variable='
insert into table(row1)
select * from OPENROWSET(''MSDASQL'',''Driver={Microsoft Text Driver (*.txt; *.csv)};
DEFAULTDIR='+#path+';rowDTERMINATOR = \n;'',''SELECT * FROM '+#fileName+''')
'
EXEC(#variable)
the problem is that some records has a ',' in the middle of the name of the client for example:
david,steven abril pulecio
and this method insert that in the table like this:
|david|
so how can i use this method or maybe use bulk insertion and evite that it cut the records when they have a ',' ?

Msg 102, Level 15, Line 1 , Incorrect syntax (however ...)

I'm running Microsoft SQL Server 2005 and I've got the following query to import the records from my csv.
However it keeps giving me this syntax error
LOAD DATA local INFILE 'C:\Users\Administrator\Downloads\update_05112013.csv' INTO TABLE dbo.Urls
FIELDS TERMINATED BY ';'
ENCLOSED BY '"'
ESCAPED BY '\\'
LINES TERMINATED BY '\n'
Perhaps I'm missing something small , probably ??
Can any of you guys see what I'm doing wrong.
SQL Server BULK INSERT is a good way to insert data in bulk (as the name suggests) but it doesn't actually support CSV files:
http://technet.microsoft.com/en-us/library/ms188609.aspx
Comma-separated value (CSV) files are not supported by SQL Server
bulk-import operations. However, in some cases, a CSV file can be used
as the data file for a bulk import of data into SQL Server.
If you can create a CSV without quotation marks or escaped characters this will work:
BULK INSERT dbo.Urls FROM 'C:\Users\Administrator\Downloads\update_05112013.csv'
WITH
(
FIELDTERMINATOR = ';',
ROWTERMINATOR = '\n'
)