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

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

Related

unable to pass variables to oracle sql file (as part of a schema name) that is being called from a shell script

getting an error on trying to pass a variable as a schema name for an sql file and I need a way to get this done.
I have noticed I do not get any error on passing a variable in a where clause of an sql statement.
I have tried with the below ways:
1)
Shell script 1:
#!/bin/bash
b=`sqlplus -silent $dbconnect #abc.sql prd01`
SQL script:
Set Heading off
Set term off
Spool xyz.csv
Select * from pkk$'&1'_02.tab1
Where
Col = 'S';
ERROR-
ORA-00933: SQL command not properly ended
Shell script 1:
#!/bin/bash
b=`sqlplus -silent $dbconnect #abc.sql prd01`
SQL script:
Set Heading off
Set term off
Spool xyz.csv
Select * from pkk$"&1"_02.tab1
Where
Col = 'S';
ERROR-
ORA-00933: SQL command not properly ended
Shell script 1:
#!/bin/bash
b=`sqlplus -silent $dbconnect #abc.sql prd01`
SQL script:
Set Heading off
Set term off
Spool xyz.csv
Select * from pkk$&1_02.tab1
Where
Col = 'S';
No error:
but waiting prompt to pass a variable
No error on passing the variable in the where clause
Shell script 1:
#!/bin/bash
b=`sqlplus -silent $dbconnect #abc.sql prd01`
SQL script:
Set Heading off
Set term off
Spool xyz.csv
Select * from pkk$prd01_02.tab1
Where
Col = '&1';
No error
In sqlplus, you need to use a '.' if the variable name is followed by something, in your case write your sql like this:
Select * from pkk$&1._02.tab1
Where
Col = 'S';
And, if you tried your script by logging in sqlplus and running it interactively, you would have seen your error.

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?

DB2 Drop multiple tables - auto-generating script

I have some very specific issue.
Target is to drop multiple tables in one schema that are older than 3 months and have certain prefix.
The difficulty is that I need to desing a script, that will generate drop statements automatically, so that I could shedule it to a crontab for daily execution.
Shortly, I need this two actions:
db2 "Select 'DROP TABLE ', tabname, ';' from syscat.tables where owner='DBUSER'" >> filename
db2 -tvf filename>log
been packed in a script that will generate the list of tables to be dropped and then drop those tables.
Actually, I have no idea how to do that... Please, give an advice.
Many thanks!
This script should provide a basis for you to move forward:
DROPFILE=/tmp/drop.$$.sql
echo ${DROPFILE}
db2 -o connect to pocdb
#
# Drop / Create tables for clean environment
#
for i in 0 1 2 3 4 5
do
db2 "drop table stkdrp.t${i}"
db2 "create table stkdrp.t${i} (f1 integer)"
done
#
# List tables, there should be six
#
db2 "select count(*) as tabcnt from syscat.tables where tabschema like 'STKDRP%' "
db2 "select tabschema, tabname from syscat.tables where tabschema like 'STKDRP%' order by tabname"
#
# Create the drop command file
#
db2 "select 'DROP TABLE ' || trim(tabschema) || '.' || trim(tabname) || ';' from syscat.tables where tabschema like 'STKDRP%'" 2>&1 | grep DROP > ${DROPFILE}
#
# Drop the tables
#
db2 -tvf ${DROPFILE}
#
# List tables, there should be zero (0)
#
db2 "select count(*) as tabcnt from syscat.tables where tabschema like 'STKDRP%' "
db2 "select tabschema, tabname from syscat.tables where tabschema like 'STKDRP%' order by tabname"
#
# Clean up the mess
#
rm -f ${DROPFILE}
db2 connect reset
db2 terminate
Results:
/tmp/drop.1607.sql
Database Connection Information
Database server = DB2/LINUXX8664 10.5.3
SQL authorization ID = DB2INST1
Local database alias = POCDB
DB21034E The command was processed as an SQL statement because it was not a
valid Command Line Processor command. During SQL processing it returned:
SQL0204N "STKDRP.T0" is an undefined name. SQLSTATE=42704
DB20000I The SQL command completed successfully.
DB21034E The command was processed as an SQL statement because it was not a
valid Command Line Processor command. During SQL processing it returned:
SQL0204N "STKDRP.T1" is an undefined name. SQLSTATE=42704
DB20000I The SQL command completed successfully.
DB21034E The command was processed as an SQL statement because it was not a
valid Command Line Processor command. During SQL processing it returned:
SQL0204N "STKDRP.T2" is an undefined name. SQLSTATE=42704
DB20000I The SQL command completed successfully.
DB21034E The command was processed as an SQL statement because it was not a
valid Command Line Processor command. During SQL processing it returned:
SQL0204N "STKDRP.T3" is an undefined name. SQLSTATE=42704
DB20000I The SQL command completed successfully.
DB21034E The command was processed as an SQL statement because it was not a
valid Command Line Processor command. During SQL processing it returned:
SQL0204N "STKDRP.T4" is an undefined name. SQLSTATE=42704
DB20000I The SQL command completed successfully.
DB21034E The command was processed as an SQL statement because it was not a
valid Command Line Processor command. During SQL processing it returned:
SQL0204N "STKDRP.T5" is an undefined name. SQLSTATE=42704
DB20000I The SQL command completed successfully.
TABCNT
-----------
6
1 record(s) selected.
TABSCHEMA TABNAME
---------- -----------
STKDRP T0
STKDRP T1
STKDRP T2
STKDRP T3
STKDRP T4
STKDRP T5
6 record(s) selected.
DROP TABLE STKDRP.T0
DB20000I The SQL command completed successfully.
DROP TABLE STKDRP.T1
DB20000I The SQL command completed successfully.
DROP TABLE STKDRP.T2
DB20000I The SQL command completed successfully.
DROP TABLE STKDRP.T3
DB20000I The SQL command completed successfully.
DROP TABLE STKDRP.T4
DB20000I The SQL command completed successfully.
DROP TABLE STKDRP.T5
DB20000I The SQL command completed successfully.
TABCNT
-----------
0
1 record(s) selected.
TABUTHEMA TABNAME
---------- -------
0 record(s) selected.
DB20000I The SQL command completed successfully.
DB20000I The TERMINATE command completed successfully.

How to include SQL code in SQL query?

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 ).