How to include SQL code in SQL query? - sql

Prior to my main select statement, I first have to create a temporary table with thousands of lines (using a select statement to get these lines automatically is not feasible in my SQL Server environment), but working in that SQL query is a nightmare of readability, as my .sql file has thousands of lines :(
Is is possible to achieve something like this ?
include('actors_tables.sql') /*including all the insert code*/
select * from #temp_actors
instead of this ?
create table #temp_actors (firstname varchar(50), lastname varchar(50))
insert into #temp_actors values ('George','Clooney')
insert into #temp_actors values ('Bill','Murray')
insert into #temp_actors values ('Bruce','Willis')
... + 1000 inserts in thousands of lines
select * from #temp_actors
Seems to me like a basic simple feature but I can't find how to achieve this ...
The server is running SQL Server 2005, and I'm using SQL Server Management Studio 2008.
Thank you for your help !
Kris.

From the command prompt, start up sqlcmd:
sqlcmd -S <server> -i C:\<your file name here>.sql -o
Or to run from sql server management studio use xp_cmdshell and sqlcmd:
EXEC xp_cmdshell 'sqlcmd -S ' + #DBServerName + ' -d ' + #DBName + ' -i ' + #FilePathName

you can use Sqlcmd in command prompt with input file (use sqlcmd -i actors_tables.sql ).

Related

Postgres COPY and SQL commands in the same script

I have the following SQL script -
--This is a function
SELECT * FROM import ('test');
TRUNCATE table some_table;
cat <<SQL
\COPY (
SELECT * from large_query
)
TO '/tmp/dash.csv' WITH DELIMITER ',' CSV HEADER
SQL
;
I am getting a parse error when I run this script like this -
psql -h host -p port -U user db -f my_file.sql
Can regular SQL statements not be combined with the \COPY command?

SQL Server 2012 table data export to excel file

I would like to export data from a SQL Server stored procedure to an Excel file. How can I achieve that?
I test like that:
insert into OPENROWSET(
'Microsoft.ACE.OLEDB.12.0',
'Excel 8.0;Database=D:\test.xlsx;;HDR=YES',
'SELECT EmpID FROM [Sheet1$]')
select * from tb1
but it returns an error:
Column name or number of supplied values does not match table definition.
I think it's because Excel doesn't have columns right? But there's no way to pre-write columns before exporting to Excel, and SQL Server can't create Excel by itself ...
I also tried with bcp:
bcp "SELECT * FROM mydb.tb1" queryout 'D:\test.xlsx' -t, -c -S . -d DESKTOP-D3PCUR7 -T
It returns error:
Incorrect syntax near 'queryout'.
How can I export table to Excel easily in SQL Server?

SQL script to generate another [INSERT] SQL script

I have a weird SQL situation in which I need to create a SQL script that I would run against database A and it would output another SQL script that would contain INSERT statements which I can then run against database B and upload the data (essentially an Export from A to B but a longer way).
I was wondering if anyone has worked on this an can suggest a way to generate INSERT statements that would contain data from [Database A].[Table Student] which can then be uploaded to [Database B].[Table Student].
Thanks a lot.
You can concat the values from student into an insert string like:
SELECT concat('Insert INTO Students VALUES(', Col1,', ', '''', Col2, '''', ')')
AS [Details]
FROM Student
WHERE ...
N.B The four single quotes is to create a single quote before and after varchar columns for example.
To generate a new SQL script from this, I'd create a cmd file with something like:
SET SERVER=YOUR_SERVER
SET DATABASE=YOUR_DB
sqlcmd -S %SERVER% -d %DATABASE% -h -1 -i Script.sql -o NewScript.sql -W
-- You Can Simple Use insert into statement
INSERT INTO [Database B].[Table Student]
SELECT * FROM [Database A].[Table Student]
WHERE StudentID NOT IN (SELECT StudentID FROM [Database B].[Table Student])
Here is one way that would insert data from one database table to other database table
INSERT INTO [DestinationDB].[dbo].Student
SELECT * FROM [SourceDB].[dbo].Student
GO
If you have access to the both databases you can do it in one query like this:
INSERT INTO [Database A].[Table Student]
OUTPUT inserted.*
INTO [Database B].[Table Student]
SELECT *
FROM [newdata];

sql insert query through text file

I'm trying to insert data from excel sheet to sql database. The query is stored in a text file as follows:
insert into [demo].[dbo].[relative]
select *
from openrowset('Microsoft.Jet.OLEDB.4.0','Excel 8.0;Database=D:\relative.xls','select * from [sheet1$]');
When I am executing the following command:
sqlcmd -S ADMIN-PC/SEXPRESS -i d:\demo.txt.
it is showing this error:
Msg 7357, Level 16, State 2, Server ADMIN-PC\SEXPRESS, Line 1
Can anyone please help in rectifying my problem.
Try using the sql server import vizard to create a new table from the xls file and then insert that data to the existing table from there. The problem you are having is maybe due to the non-compatibility between 64bit sql instance and 32 bit excel.
Or try using bcp
bcp demo.dbo.relative in "D:\relative.xls" -c -T
There is another way to get the same result..
create a temp table.
declare #sometable table (value varchar(50), translation varchar(max))
select * into #sometable from YOUR_DATABASE_TABLE (nolock)
Then, do your OPENROWSET, BCP, etc. from here..
You can create a shell script which will automatically read the insert commands from the .csv file and then write it to the database. If you want I can help you up with it. What you just need to do is to write all the insert statements in the .csv file.
#!/bin/ksh
sqlplus -silent /nolog << EOF > /dev/null
username/pwd#"Connection String"
set linesize 0;
set pagesize 0;
set echo off;
while read line; do
A=`echo "$line" | awk -F" " {print 1}`
and so on depends on the number of words in the insert statements.
$A $B
done < your_insert_statements.csv
It will read the .csv file and automatically insert the records in the database.

Drop all tables in a SQL Server database from Batch file?

I have this batch file that outputs a list of all the tables to a file. I am looking for the command that will input this list and generate a whole list of drop statements to drop all the tables with?
:: droptables.bat
set SQLVER=100
if NOT EXIST "%PROGRAMFILES%\Microsoft SQL Server\100\Tools\BINN\osql.exe" (
#echo MS SQL Server 2008 not found.
set SQLVER=90
if NOT EXIST "%PROGRAMFILES%\Microsoft SQL Server\90\Tools\BINN\osql.exe" (
#echo MS SQL Server 2005 not found.
set SQLVER=80
if NOT EXIST "%PROGRAMFILES%\Microsoft SQL Server\80\Tools\BINN\osql.exe" (
#echo MS SQL Server is not yet installed.
pause
exit
)
)
)
#echo Your SQL Server version is %SQLVER% (100=2008,90=2005, and 80=2000)
if exist "%PROGRAMFILES%\Microsoft SQL Server\%SQLVER%\Tools\BINN\osql.exe" (
"%PROGRAMFILES%\Microsoft SQL Server\%SQLVER%\Tools\BINN\osql" -E
-d "%PROJECT%PD_FSDB_ECitation" -h-1 -Q "select name from sysobjects where
type='U' order by name;" -o tableList.txt
The above query needs to be changed to create a list of drop statements instead of just table names. The tableList.sql file is just a simple list of drop table statements.
After generating the queryList.sql, then I want to run it like so:
osql -E -h-1 -i C:\MyFolder\queryList.txt
I know there is a way to generate a list of SQL statements from a SQL statement but I don't remember how to do it.
Why don't use just use the system stored proc sp_msforeachtable?
Run the following from your osql and you can bypass a lot of the extra work you are doing:
USE <databasename>
exec sp_msforeachtable 'DROP TABLE ?'
This proc basically builds a cursor and executes the query inside the single quotes once for each table, replacing ? with the schema-qualified table name, like dbo.table.
Run the following from your SQL. It is simple and fast to delete tables from your DB:
USE <databasename>
exec sp_msforeachtable 'DROP TABLE ?'
I don't know if there is a command to do it but you can change your select statement so that it creates the drop statement for you:
select '--DROP TABLE ' + name + CHAR(10) + 'DROP TABLE ' + name + ' GO' from sysobjects where type='U'
EDIT: After comment with regards to schema not specified:
SELECT '--DROP TABLE ' + TABLE_NAME + CHAR(10) + 'DROP TABLE ' + QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME)
FROM INFORMATION_SCHEMA.TABLES
EDIT: As Remus suggested in the comments, added quotename to make it less vulnerable to sql injection
Here is how I did it:
set SQLVER=100
if NOT EXIST "%PROGRAMFILES%\Microsoft SQL Server\100\Tools\BINN\osql.exe" (
#echo MS SQL Server 2008 not found.
set SQLVER=90
if NOT EXIST "%PROGRAMFILES%\Microsoft SQL Server\90\Tools\BINN\osql.exe" (
#echo MS SQL Server 2005 not found.
set SQLVER=80
if NOT EXIST "%PROGRAMFILES%\Microsoft SQL Server\80\Tools\BINN\osql.exe" (
#echo MS SQL Server is not yet installed.
pause
exit
)
)
)
#echo Your SQL Server version is %SQLVER% (100=2008,90=2005, and 80=2000)
if exist "%PROGRAMFILES%\Microsoft SQL Server\%SQLVER%\Tools\BINN\osql.exe" (
"%PROGRAMFILES%\Microsoft SQL Server\%SQLVER%\Tools\BINN\osql" -E -h-1
-d MYDB -Q "select 'DROP TABLE ' + CAST(name AS
VARCHAR(30)) + ';' from sysobjects where type='U';" -o queries.sql
:: remove sql result count line
type queries.sql | findstr /V rows > queryList.sql
:: rename Identity table in the sql script because it uses a keyword
type queryList.sql | findstr /V /C:"TABLE Identity" > runQueries.sql
echo DROP TABLE [Identity]; >> runQueries.sql
"%PROGRAMFILES%\Microsoft SQL Server\%SQLVER%\Tools\BINN\osql" -E -h-1
-d MYDB -i runQueries.sql -o dropResults1.txt
)
pause
:: Cleanup
del queryList.sql
del dropResults1.txt
del dropResults2.txt
del runQueries.sql
del queries.sql
exit