Export contents of SQL Server 2008 R2 table to CSV WITHOUT xp_cmdshell - sql-server-2008-r2

I need to export the contents of a SQL SErver 2008 R2 Express table to a CSV or TXT file.
I cannot enable xp_cmdshell nor can I allow ad hoc distributed queries.
It needs to be executable from a trigger on one of the tables.

USE master;
GO
EXEC sp_configure 'show advanced option', '1';
RECONFIGURE;
EXEC sp_configure;
EXEC sp_configure 'Ad Hoc Distributed Queries', '1';
RECONFIGURE;
EXEC sp_configure;
INSERT INTO OPENROWSET('Microsoft.Jet.OLEDB.4.0',
'Text;Database=C:\Temp\;HDR=Yes;',
'SELECT * FROM test.csv')
(object_id, name)
SELECT 'object_id', 'name'
UNION ALL
SELECT object_id, name
FROM sys.tables
--This require csv file to be there at location
Follow this Link , if you face any problem while insertion.
Once working you use same script in trigger.

Related

How to deal with error:SQL Error [58P01]?

I'm learning PostgreSQL, and i run into problem:
I have created table and trying to export it, but I have all the time same error
SQL Error [58P01]: ERROR: could not open file "D:\Janis\Mācības\SQL\Test\typestest.txt" for writing: No such file or directory
Hint: COPY TO instructs the PostgreSQL server process to write a file. You may want a client-side facility such as psql's \copy.
Script that I'm running:
CREATE TABLE char_data_types (
varchar_column varchar(10),
char_column char(10),
text_column text
);
INSERT INTO char_data_types
VALUES
('abc', 'abc', 'abc'),
('defghi', 'defghi', 'defghi');
COPY char_data_types TO 'D:\Janis\Mācības\SQL\Test\typestest.txt'
WITH (FORMAT CSV, HEADER, DELIMITER '|');
I have taken off all possible security restriction from file typestest.txt
There is no directory D:\Janis\Mācības\SQL\Test on the PostgreSQL server. Note that COPY writes to the database server, no the client (the statement runs on the server, and the server cannot access the client machine).
To export the data to the client machine, you have to use psql so that you can use \copy:
\copy char_data_types TO 'D:\Janis\Mācības\SQL\Test\typestest.txt' WITH (FORMAT CSV, HEADER, DELIMITER '|')
The command has to be in a single line.

Update SP Definition reading from file and run dynamic SQL, deal with EOL

Hi I need to create new definitions for SP having their source in external physical files (imported from other TFS site, have 1000+ of them). I thought I solved this problem on my first post.
But now I see another problem if you read my file into single line I got an error 'CREATE/ALTER PROCEDURE' must be the first statement in a query batch. I need bring end of of line into my #sql
The only solution I see now read all lines into table with multiple rows and then concatenate them ? which is quite complex. Is there any way to deal with \n' in more compact way ? The code below produce error. GO should be on separate line alone. My global task to read 100+ files and run code inside.
And I don't have any access to that source DB they came from, just need to deal with flat files. Don't have any option to do Right Click on database, etc..
I think probably it's wrong way at all, I can bring those files into TFS/SQL project and do something out of TFS, probably should be be some way to apply new codes...(?)
CREATE TABLE #imp (Col varchar(max))
BULK INSERT #imp
FROM '//TFSNetwork/log/Install/sp_Test02.sql'
WITH (ROWTERMINATOR = '\nzzzzz') ---<< ?????
select top 1 #Sql = Col from #imp
EXEC (#sql);
--- This is content of my sample file sp_Test02
USE MAGDA_Test
GO
SET ANSI_NULLS ON
GO
/*
Description:
*/
CREATE PROCEDURE [dbo].[sp_Test]
AS
BEGIN
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;
SET NOCOUNT ON;
SELECT GETDATE() AS TS
END
Actual result: Msg 111, Level 15, State 1, Line 1
'CREATE/ALTER PROCEDURE' must be the first statement in a query batch.
Expected Result: SP Created OK
--I suspect that SSMS/ doing some own stuff on line breaks, b'z this in this test we still have single line
DECLARE #sql NVARCHAR(MAX) = 'This is line 1.' + CHAR(13)+CHAR(10) + 'This is line 2.'
SELECT #sql --- 1 line
Print #sql --- 2 lineS
Use sqlcmd you can compose multiple entries for all files in .bat file and run in single click. This way it works fine with all CR/LF. Just get enough permissions for your db.
Below is the contents of simple .bat file.Can use universal CREATE OR ALTER PROCEDURE inside your .sql
#echo off
sqlcmd -S dbServ10 -U UserAcct -P UserPsw -i "//TFSNetwork/log/Install/sp_Test01.sql"
sqlcmd -S dbServ10 -U UserAcct -P UserPsw -i "//TFSNetwork/log/Install/sp_Test02.sql"
...
...
sqlcmd -S dbServ10 -U UserAcct -P UserPsw -i "//TFSNetwork/log/Install/sp_Test100.sql"

How to append new data to the log file in PostgreSQL

I am migrating oracle code to postgresql where i need to append the query to existing log file.
Basically i want equivalent of oracle command " SPOOL test.log APPEND " in PostgreSQL . Is there a way to do that?
I tried to append new data to the log file using \o or \o+ or copy in PostgreSQL but it overwrites the log file.
My code is something like this :
Oracle:
spool test.log
select uid from users where uid='1111';
spool off
select sysdate from dual;
//other business logic code
-
spool test.log append
select balance from balances where uid='1111';
spool off
Postgresql:
\o test.log
select uid from users where uid='1111';
\o
select current_date;
//other business logic code
-
\o test.log
select balance from balances where uid='1111';
\o
I want the two queries in \o block to append to same file in PostgreSQL.
You could use
\o | cat >> test.log
on UNIX platforms.

How could one duplicate the same environment configuration as a database server?

I'm interested in making my local postgres server config match the production one. Given a psql connection to it, would it be possible to run some queries and extract the relevant performance options? Alternatively, if this is not possible, does anyone know the configuration options for heroku's paid postgres plans?
This will show you all settings for the server.
SELECT current_setting(name), *
FROM pg_catalog.pg_settings
Then you can look at the postgresql.conf to see what has been set manually.
If you don't have any access to the postgresql.conf, use the above query on some other server and see what's different :)
This should work as long as you have permission to read the remote config file (change the delimiter at a pinch).
create table conf(
line text
);
do $$
begin
execute
format(
'copy conf from ''%s'' delimiter ''|''',
current_setting('config_file'));
end $$;
select * from conf;
Two maybe helpful tips.
-- skip empty and commented lines:
select line from conf
where line != '' and ltrim(line, e' \t') not like '#%';
-- copy conf to file:
copy (select replace(line, e'\t', ' ') from conf) to 'c:/data/postgres.conf';

combining two .bat files Dos and T-SQL

What I would like is to combine the two files into one bat file but currently sqlcmd stops with the sqlqcmd prompt and the SQL is not running.
Ouch server went bang so I need to put contingency in place PDQ
I normally use SQL server agent with some jobs but while the new server is being sorted. I only have SQL express No SQL server agent.
Fine my so I have created a backup.bat it works fine in cmd calling backup.sql the sql send it to another drive.
The statement I used is:-
Sqlcmd –S \mypc\instancename –i C:\backup.sql( as I am local window authentication is fine)
This is so that i can use task scheduler in not very friendly windows 7
At the moment I have a .bat file calling a .sql file.
Backup.bat
Sqlcmd –S \mypc\instancename –i C:\backup.sql
Backup.sql
BACKUP DATABASE [Northwind] TO DISK = N'\\nas1\backup\northwind.bak' WITH NOFORMAT, INIT, NAME = N'Northwind-Full Database Backup', SKIP, NOREWIND, NOUNLOAD, STATS = 10
GO
declare #backupSetId as int
select #backupSetId = position from msdb..backupset where database_name=N'Northwind' and backup_set_id=(select max(backup_set_id) from msdb..backupset where database_name=N'Northwind' )
if #backupSetId is null begin raiserror(N'Verify failed. Backup information for database ''Northwind'' not found.', 16, 1) end
RESTORE VERIFYONLY FROM DISK = N'\\nas1\backup\Northwind.bak' WITH FILE = #backupSetId, NOUNLOAD, NOREWIND
GO
What I want is to combine the two files into one bat file but currently sqlcmd stops with the sqlcmd prompt and the SQL is not running.
Sqlcmd –S \mypc\instancename
BACKUP DATABASE [Northwind] TO DISK = N'\\nas1\backup\northwind.bak' WITH NOFORMAT, INIT, NAME = N'Northwind-Full Database Backup', SKIP, NOREWIND, NOUNLOAD, STATS = 10
GO
declare #backupSetId as int
select #backupSetId = position from msdb..backupset where database_name=N'Northwind' and backup_set_id=(select max(backup_set_id) from msdb..backupset where database_name=N'Northwind' )
if #backupSetId is null begin raiserror(N'Verify failed. Backup information for database ''Northwind'' not found.', 16, 1) end
RESTORE VERIFYONLY FROM DISK = N'\\nas1\backup\Northwind.bak' WITH FILE = #backupSetId, NOUNLOAD, NOREWIND
GO
Add
quit
as the last line of the .SQL files.
I found using two files works