SQL Server query - copy all tables from query into database - sql

I have question about copy tables from a query into other database.
I use this query in SQL Server:
SELECT * FROM information_schema.tables WHERE TABLENAME = '2000'
This query returns tables. And I would like to copy all the returned tables into my other database.
Thank you in advance.

have a look at sp_MSforeachtable and feed your table names into it from information_schema.tables
there is a good example here to get you started sp_MSforeachtable example
Another example that can be modified is here
This could be amended to suit your needs:
Exec sp_MSforeachtable
#command1 = "SELECT COUNT(*) AS [?] FROM ?",
#whereand = "and uid = (SELECT schema_id FROM sys.schemas WHERE name = 'dbo')
and o.name LIKE 'IIN%'"
Replace #command1 with your copy code (something like SELECT * INTO ... and replace #whereand with your filter for your tables or an IN statement if you have a list.

Related

How to copy a table from a linked server into the main database only on the condition that the table does not already exist?

I am using SQL Server 2012 and I have the following T-SQL query:
USE MyDatabase
INSERT INTO [Table1]
SELECT *
FROM [xxx.xx.x.xx].[xxx].[dbo].[Table1]
I would like to modify this query so that it copies Table1 into MyDatabase only if that table does not already exist in MyDatabase.
I've had a look here but I can't figure out how to migrate the solutions into my problem: Check if table exists in SQL Server
How can I achieve this?
This should do it:
IF (NOT EXISTS (SELECT *
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME = 'Table1'))
BEGIN
INSERT INTO [Table1]
SELECT *
FROM [xxx.xx.x.xx].[xxx].[dbo].[Table1]
END
More details and approaches you can read here:
Check if table exists in SQL Server

SQL Server 2012- Using sp_msforeachdb

I want to run a SELECT statement on only some specific databases. The list of databases is returned by this query:
DECLARE #OneWeekAgo DATETIME
SELECT #OneWeekAgo = DATEADD(week,-1,GETDATE())
select distinct DB_NAME(database_id) DatabaseName
into #temp
from sys.dm_db_index_usage_stats
where DB_NAME(database_id) like 'TTT[_][a-z]%'
and DB_NAME(database_id) not like '%test%'
and last_user_update > #OneWeekAgo
Now on all of these databases returned, I want to run a simple query:
SELECT *
FROM TTT_Clients
WHERE country like 'SWEDEN'
How do I do that? I get errors in the "IN (SELECT DISTINCT...)" line using something like this:
exec sp_msforeachdb ' use [?] IF ''?'' in (select distinct DB_NAME(database_id) DatabaseName
from sys.dm_db_index_usage_stats
where DB_NAME(database_id) like ''TTT[_][a-z]%''
and DB_NAME(database_id) not like ''%test%'')
BEGIN
SELECT * FROM TTT_Clients WHERE country like ''SWEDEN''
END
You didn't specify the error, and I don't know this for sure, but I'm guessing that sys.dm_db_index_usage_stats returns the same information regardless of database you are using (server wide view).
I think you want something like this...
exec sp_msforeachdb ' use [?];
IF ('[?]' NOT LIKE ''%test%'' AND EXISTS(SELECT * FROM sys.tables WHERE name LIKE ''TTT[_][a-z]%''))
BEGIN
SELECT * FROM TTT_Clients WHERE country like ''SWEDEN''
END
'
Re-using your filters, I don't know if they are correct or not. Basically we are checking if the table in question exists in the database. Since you are only selecting from TTT_Clients I would suggest just filtering WHERE name = ''TTT_Clients'' rather than that regex that just matches it.

Get the DDL of all the tables in teradata as a resultset

Is there a way that I can extract the DDL of all the tables in one single query.
select DatabaseName,TableName,RequestText from db.tables;
gives the database name , table name and the last DDL on the table. But is it possible to get DDL to create the tables in form of resultset to a query instead of querying show db.tableName several times
You can try this:
sel 'show table ' || databasename ||'.'|| tablename ||';'
from dbc.tables where databasename = 'dbname' and tablekind = 'T';
and then you can execute the output of this query to get the DDL like:
show table dbname.sometablename;

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

Select all columns from all tables in SQL Server 2008

How can I Select all columns from all tables from the DB, like:
Select * From *
in SQL Server 2008???
The table list it´s very very big, and have so many columns, is it possible to do it without writing the column names?
Or maybe make a select that returns the name of the tables.
This SQL will do this...
DECLARE #SQL AS VarChar(MAX)
SET #SQL = ''
SELECT #SQL = #SQL + 'SELECT * FROM ' + TABLE_SCHEMA + '.[' + TABLE_NAME + ']' + CHAR(13)
FROM INFORMATION_SCHEMA.TABLES
EXEC (#SQL)
Try this, works fine
SELECT * FROM INFORMATION_SCHEMA.COLUMNS
then you could add
WHERE TABLE_NAME LIKE '' AND COLUMN_NAME LIKE ''
SELECT t.name AS table_name,
SCHEMA_NAME(schema_id) AS schema_name,
c.name AS column_name
FROM sys.tables AS t
INNER JOIN sys.columns c ON t.OBJECT_ID = c.OBJECT_ID where t.name = 'ProductItem' AND C.name like '%retail%'
ORDER BY schema_name, table_name
It is possible to retrieve the name of all columns from sys.columns
It is possible to retrieve the name of all table from sys.tables
But is impossible to retrieve all the data from all the tables. As soon as more than one table is involved in a query, a JOIN is necessary. Unless join conditions are provided, tables are joined as full Cartesian product, meaning each row from each table is matched with each row from ll other tables. Such a query as you request would produce for 10 tables with 10 records each no less than 10e10 records, ie. 100 billion records. I'm sure you don't want this.
Perhaps if you explain what you what to achieve, not how, we can help better.
To select * from each table, one after another, you can use the undocumented but well known sp_msforeachtable:
sp_msforeachtable 'select * from ?'
If you are going to send to Excel, I would suggest you use the export wizard and simply select all the tables there. In the object browser, put your cursor on the database name and right click. Chose Tasks - Export Data and follow the wizard. WHy anyone would want an entire database in Excel is beyond me, but that's the best way. If you need to do it more than once you can save the export in an SSIS package.
In SQL Server 2016 Management Studio ( Version: 13.0.15900.1), to get all column names in a specified table, below is the syntax:
**Select name from [YourDatabaseName].[sys].[all_columns]
where object_id=(Select object_id from [YourDatabaseName].[sys].[tables]
where name='YourTableName')**