Print first 10 entries from each table in SQL Server database with empty lines between tables - sql

I can open each table and do select top 10 * from table_name for each table and copy-paste results to Notepad. How can I automate it to have for each table print first 10 rows, followed by empty line in one output window?

This will form a statement to print first 10 rows of each table. Execute it for the desired output.
select 'Select Top 10 * From ' + SCHEMA_NAME(schema_id) + '.' + name
from sys.objects
where type = 'U'
Follow this method to get the desired output to one file: Is there any straightforward way to output text files (or CSV) from SQL Server?
Briefly: Tools-> Options-> Query results->results to text

Related

How to write a query which selects from a table that is returned by another query

I have table which has basically 2 rows containing the name of failure and the main table i want to write a query such that
Select main
from xyz
will return the table name like abc.
Now I want to get the data from the abc table
Select *
from
(select main
from xyz)
which returns abc.
How can I write it ?
You must use dynamic sql.
Note, that you can't use "SELECT to nowhere" in a compound statement in Db2. That is, the following code is erroneous.
BEGIN
SELECT * FROM MYTAB;
END#
This is why you need to store the result of SELECT somewhere. You may use Global Temporary Tables for that presuming, that USER TEMPORARY TABLESPASE is available to use for your user.
--#SET TERMINATOR #
BEGIN
DECLARE V_STMT VARCHAR (500);
SELECT
'DECLARE GLOBAL TEMPORARY TABLE SESSION.RESULT'
|| ' AS (SELECT * FROM '
|| MAIN
|| ') WITH DATA WITH REPLACE '
|| 'ON COMMIT PRESERVE ROWS NOT LOOGED'
INTO V_STMT
FROM XYZ
-- place your WHERE clause here if needed
FETCH FIRST 1 ROW ONLY
;
EXECUTE IMMEDIATE V_STMT;
END
#
SELECT * FROM SESSION.RESULT
#
dbfiddle link.
Here is a solution on stack that shows how to get the table names from your database
DB2 Query to retrieve all table names for a given schema
Then you could take your failure table and join into it based off of the table name, that should match your errors to the table that match on the table name. I'm not a 100% sure of your question but I think this is what you are asking.
The inner system query has schema and name. Type is T for table. See IBM link below for column reference. You could run the query wide open in the inner query to look for the tables you want. I would recommend using schema to isolate your search.
https://www.ibm.com/docs/en/db2-for-zos/11?topic=tables-systables
SELECT
ft.*
, st.*
FROM [FailureTable] as ft
INNER JOIN
(
select * from sysibm.systables
where CREATOR = 'SCHEMA'
and name like '%CUR%'
and type = 'T'
) st
ON st.[name] = ft.[tablename]
You can try
DECLARE #tableName VARCHAR(50);
SELECT #tableName = main
FROM xyx
EXEC('SELECT * FROM ' + 'dbo.' + #tableName)
Dont forget to add validation if #tableName doesnt get populated

Combining tables into one

We have a horribly designed database that has procedures in it that generate new tables every week, and has been doing so for a couple of years. It's got a SQL script that gets 200+ columns of data via queries on various tables, dumps it all into a single table called Selections, and then after it's done you have to manually rename that table (Selections_Week001, Selections_Week002, etc) every week. Now we have around 100+ tables. What I want to do is put all that data into one table, with a column indicating its original source table (001, 002, etc), so I can then get rid of all those individual tables. Is there a way to do this using some SQL script, or am I going to have to manually edit and run 100 append queries?
Try this, for me worked well at test data:
select *
into Selections_Total
from Selections_Week001
where 1=0
alter table Selections_Total
add Original_Table varchar(64)
--select * From Selections_Total
declare #sql varchar(max)
select #sql = COALESCE(#sql + ' UNION ALL select *, ''' + name + ''' from ', 'select *, ''' + name + ''' from ') + name
from sys.tables where name like 'Selections_Week%'
--select #sql
insert into Selections_Total
exec(#sql)
UPD: missed with a column indicating its original source table at first. Now fixed.

export oracle table in a csv file [duplicate]

This question already has answers here:
How do I spool to a CSV formatted file using SQLPLUS?
(16 answers)
Closed 5 years ago.
I am writting an sql script to export the content of tables in csv files (one table per file). I managed to write a successful script, thanks to the spool function like this :
spool export.csv append
select 'fielda;fieldb;...' from dual
select fielda,fieldb,.... from table
spool off.
The first problem with this, is that I have to do a select from dual to get only the fields name on the first line.
The second problem with this, is that I have to write each field, and it becomes very painfull when you have 10 tables each having more than 20 fields. So my question was, is there any pl sql function, that takes in parameter only the table name, and export the full content in a csv file.
Thanks in advance.
Below might work for you
set termout off
set serveroutput off
set feedback off
set colsep ';'
set lines 100000
set pagesize 0
set echo off
set feedback off
spool on
spool D:\csv_generator_tmp.sql
select qr from
(select 'select '||a.column_name||'||'';''||' qr,a.COLUMN_ID
from user_tab_cols a
where a.table_name = upper('cust')
and a.column_id=1
union
select b.column_name||'||'';''||',b.COLUMN_ID
from user_tab_cols b
where b.table_name = upper('cust') and b.column_id<>1
and b.column_id<>(select max(c.column_id) from user_tab_cols c)
union
select d.column_name||' from cust;',d.COLUMN_ID
from user_tab_cols d
where d.table_name = upper('cust')
and d.column_id=(select max(d.column_id) from user_tab_cols d))
order by column_id asc;
spool off;
spool on
spool D:\cust.csv
#D:\csv_generator_tmp.sql
spool off;
/
No but you can use user_tables and user_tab_cols to select the columns for tables of interest:
select utc.table_name, utc.column_name
from user_tab_cols utc
where utc.table_name = 'CIRCUIT'
You could manage this through a cursor and generate your select columns. You can then execute this query.
Its better to go with UTL_FILE. I would refer to user the Ask tom link https://asktom.oracle.com/pls/asktom/f?p=100:11:0::::p11_question_id:88212348059
with that you can create the file regularly by calling the function.
You can use Python and cx_Oracle module to extract data to disk in CSV format.
Here’s how you connect to Oracle using cx_Oracle:
constr='scott/tiger#localhost:1521/ORCL12'
con = cx_Oracle.connect(constr)
cur = con.cursor()
After data fetch you can loop through Python list and save data in CSV format.
for i, chunk in enumerate(chunks(cur)):
f_out.write('\n'.join([column_delimiter.join(row[0]) for row in chunk]))
f_out.write('\n')
I used this approach when I wrote TableHunter-For-Oracle

export txt file with all parameter values during the report execution

I've developed one report in Report Builder 3.0 , report server being SRSS 2008 R2. This report has one report parameter named id_product. There are two data sets available. One data set is for populating the report table. In the second data set I'm trying to export the id_product. The below query works fine only for single valued parameter id_product, this query being used in the second data set Report pops-up an error when trying to run the report for multiple products at the same time. I looked in SQL Profiler and it seems like inserting the parameter values in the global temporary table is not possible using the current code.
I'm aware of the VB Expression named Join but in such case I'm not sure if I can use it. It would be great if I can use this kind of expression. This way I would not create the data set anymore.
Current query:
drop table ##SelectedValues
create table ##SelectedValues(id_product nvarchar(max))
insert into ##SelectedValues(#id_product)
exec xp_cmdshell 'bcp "select ''id_product''
union all select * from ##SelectedValues" queryout "G:\Report\sqloutput.csv" -c -T -t'
Input: ProductId parameter values : 12, 16, 20
Desired output in csv:
id_product
12
16
20
You can either use a split function that parses the comma delimited string to table rows, or you can use my favorite, dynamic sql! :)
if object_id('tempdb..#SelectedValues') is not null
drop table #SelectedValues
create table #SelectedValues(id_product nvarchar(max))
declare #id_product nvarchar(max),#sql nvarchar(max)
set #id_product = '12, 16, 20'
set #sql =
'select ''' + replace(#id_product,', ',''' union all select ''') + ''''
insert into #SelectedValues(id_product) exec(#sql)
select * from #SelectedValues

Querying the same table for a list of databases in MS SQL Server

This is my first time posting on SO, so please go easy!
I'm attempting to write a SQL script that queries the same table for a list of databases in a single SQL Server instance.
I have successfully queried the list of databases that I required using the following, and inserting this data into a temp table.
Select name Into #Versions
From sys.databases
Where name Like 'Master%'
Master is suffixed with numerical values to identify different environments.
Select * From #Versions
Drop Table #Versions
The table name I am trying to query, is the same in each of the databases, and I want to extract the newest value from this table and insert it into the temp table for each of the database names returned.
I have tried researching this but to no avail. I am fairly comfy with SQL but I fear I could be out of my depth here.
You can do the following. Once you have the list of your databases, you can build up the query (you need to edit it for your purpose).
Select name Into #Versions
From sys.databases
Where name Like 'test%'
declare #sql as varchar(max) = ''
select #sql = #sql + 'INSERT INTO sometable SELECT TOP 1 * FROM ' + name + '..sourcetable ORDER BY somedate DESC; '
FROM #Versions
exec (#sql)
Drop Table #Versions
Look at The undocumented sp_MSforeachdb procedure and here