How to get multiple SQL Tables structure (T-SQL) into excel sheet? - sql-server

I have to take 198 SQL Tables structures. Normally, I know about SP_HELP and ALT+F1 to get single table structure.
How can i get structure multiple tables? If i provide list of table names, output should be structure(Table name(field name, Data type, Length)) of all those tables.
I have only read access to SQL DB.
And, I am new to SQL.
Environment details:
Client Tool: Microsoft SQL Server Management Studio 2014
I have searched in SO, there are answers for single table. But, that doesn't solve my question.

This query will return a list of all tables and their columns with a lot of details about data_type, size, nullability and so on:
USE YourDatabaseNameHere;
SELECT t.TABLE_TYPE, c.*
FROM INFORMATION_SCHEMA.TABLES t
INNER JOIN INFORMATION_SCHEMA.COLUMNS c ON t.TABLE_SCHEMA=c.TABLE_SCHEMA
AND t.TABLE_NAME=c.TABLE_NAME
WHERE t.TABLE_TYPE = 'BASE TABLE'; --With 'VIEW' you'd find views, or just omit the WHERE...
You can use a simple Excel to connect to the database and read this result into a Sheet.
UPDATE
Did not read, that you can use SSMS. Just paste the query into a new query window and execute it. The result can be copy-pasted into excel...

I suggest to use DB Schema tool, which is used to design the database and understand the existing relational database mapping.

By using SQL Server 2008 R2
This will create a script for you then you will be able to run it on other sql server it will create the same Data Base with all talbes.
Right Click On Data Base Name
Go to Task
Go to Generate
Scripts SQL Server 2008 R2 DataBase Image
Next > Next > Next > SetYourPath Next > Finish
first Pic second Pic 3rd Pic 4th Pic 5th Pic

Related

Import SQL tables as data into access Db

I have a SQL database (lets use northwind), that has a number of tables (unknown number of tables). I would like to import these tables into a MS access database as DATA (not tables) into a MTT_Table
All standard imports, creates the table as a physical table within ms access and not as data.
I have a table in MS Access that needs to store all the names of tables in other systems - not sure if that makes sense
Is there any way to read an infinite number of tables and populate them as data, using an odbc connection all through VBA
Expected output would be to see the table names as data values, and potentially able to populate the MS access row with metadata about the table
Use information schema to create a view in SQL server:
CREATE VIEW dbo.Sample_View
AS
SELECT TABLE_NAME
FROM [Your_Database].INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE'
Now import this view to access following the steps in this link
Your question is a bit broad (what information do you want from tables), but generally can be achieved by querying the INFORMATION_SCHEMA meta-tables over ODBC.
SELECT * INTO MTT_Table
FROM [ODBC;Driver={SQL Server};Server=my\server;Database=myDb;Trusted_Connection=Yes;].INFORMATION_SCHEMA.TABLES

Run query on sql server through teradata and store result in teradata

I have one table in SQL server and 5 tables in Teradata.I want to join those 5 table in teradata with sql server table and store result in Teradata table.
I have sql server name but i dont know how to simultaneously run a query both on sql server and teradata.
i want to do this:
sql server table query
Select distinct store
from store_Desc
teradata tables:
select cmp_id,state,sde
from xyz
where store in (
select distinct store
from sql server table)
You can create a table (or a volatile table if you do not have write privileges) to do this. Export result from SQL Server as text or into the language of your choice.
CREATE VOLATILE TABLE store_table (
column_1 datatype_1,
column_2 datatype_2,
...
column_n datatype_n);
You may need to add ON COMMIT PRESERVE ROWS before the ; to the above depending on your transaction settings.
From a language you can loop the below or do an execute many.
INSERT INTO store_table VALUES(value_1, value_2, ..., value_n);
Or you can use the import from text using Teradata SQL Assistant by going to File and selecting Import. Then execute the below and navigate to your file.
INSERT INTO store_table VALUES(?, ?, ..., n);
Once you have inserted your data you can query it by simply referencing the table name.
SELECT cmp_id,state,sde
FROM xyz
WHERE store IN(
SELECT store
FROM store_table)
The DISTINCT function is most easily done on export from SQL Server to minimize the rows you need to upload.
EDIT:
If you are doing this many times you can do this with a script, here is a very simple example in Python:
import pyodbc
con_ss = pyodbc.connect('sql_server_odbc_connection_string...')
crs_ss = con_ss.cursor()
con_td = pyodbc.connect('teradata_odbc_connection_string...')
crs_td = con_td.cursor()
# pull data for sql server
data_ss = crs_ss.execute('''
SELECT distinct store AS store
from store_Desc
''').fetchall()
# create table in teradata
crs_td.execute('''
CREATE VOLATILE TABLE store_table (
store DEC(4, 0)
) PRIMARY INDEX (store)
ON COMMIT PRESERVE ROWS;''')
con_td.commit()
# insert values; you can also use an execute many, but this is easier to read...
for row in data_ss:
crs_td.execute('''INSERT INTO store_table VALUES(?)''', row)
con_td.commit()
# get final data
data_td = crs_td.execute('''SELECT cmp_id,state,sde
FROM xyz
WHERE store IN(
SELECT store
FROM store_table);''').fetchall()
# from here write to file or whatever you would like.
Is fetching data from the Sql Server through ODBC an option?
The best option may be to use Teradata Parallel Transporter (TPT) to fetch data from SQL Server using its ODBC operator (as a producer) combined with Load or Update operator as the consumer to insert it into an intermediate table on Teradata. You must then perform rest of the operations on Teradata. For the rest of the operations, you can use BTEQ/SQLA to store the results in the final Teradata table. You can also put the same SQL in TPT's DDL operator instead of BTEQ/SQLA and get it done in a single job script.
To allow use of tables residing on separate DB environments (in your case SQL-Server and Teradata) in a single select statement, Teradata has recently released Teradata Query Grid. But I'm not sure about exact level of support for SQL-Server and it will involve licensing hassle and quite a learning curve to do this simple job.

SQL Server Linked Server Example Query

While in Management Studio, I am trying to run a query/do a join between two linked servers.
Is this a correct syntax using linked db servers:
select foo.id
from databaseserver1.db1.table1 foo,
databaseserver2.db1.table1 bar
where foo.name=bar.name
Basically, do you just preface the db server name to the db.table ?
The format should probably be:
<server>.<database>.<schema>.<table>
For example:
DatabaseServer1.db1.dbo.table1
Update: I know this is an old question and the answer I have is correct; however, I think any one else stumbling upon this should know a few things.
Namely, when querying against a linked server in a join situation the ENTIRE table from the linked server will likely be downloaded to the server the query is executing from in order to do the join operation. In the OP's case, both table1 from DB1 and table1 from DB2 will be transferred in their entirety to the server executing the query, presumably named DB3.
If you have large tables, this may result in an operation that takes a long time to execute. After all it is now constrained by network traffic speeds which is orders of magnitude slower than memory or even disk transfer speeds.
If possible, perform a single query against the remote server, without joining to a local table, to pull the data you need into a temp table. Then query off of that.
If that's not possible then you need to look at the various things that would cause SQL server to have to load the entire table locally. For example using GETDATE() or even certain joins. Others performance killers include not giving appropriate rights.
See http://thomaslarock.com/2013/05/top-3-performance-killers-for-linked-server-queries/ for some more info.
SELECT * FROM OPENQUERY([SERVER_NAME], 'SELECT * FROM DATABASE_NAME..TABLENAME')
This may help you.
For those having trouble with these other answers , try OPENQUERY
Example:
SELECT * FROM OPENQUERY([LinkedServer], 'select * from [DBName].[schema].[tablename]')
If you still find issue with <server>.<database>.<schema>.<table>
Enclose server name in []
You need to specify the schema/owner (dbo by default) as part of the reference. Also, it would be preferable to use the newer (ANSI-92) join style.
select foo.id
from databaseserver1.db1.dbo.table1 foo
inner join databaseserver2.db1.dbo.table1 bar
on foo.name = bar.name
select * from [Server].[database].[schema].[tablename]
This is the correct way to call.
Be sure to verify that the servers are linked before executing the query!
To check for linked servers call:
EXEC sys.sp_linkedservers
right click on a table and click script table as select
select name from drsql01.test.dbo.employee
drslq01 is servernmae --linked serer
test is database name
dbo is schema -default schema
employee is table name
I hope it helps to understand, how to execute query for linked server
Usually direct queries should not be used in case of linked server because it heavily use temp database of SQL server. At first step data is retrieved into temp DB then filtering occur. There are many threads about this. It is better to use open OPENQUERY because it passes SQL to the source linked server and then it return filtered results e.g.
SELECT *
FROM OPENQUERY(Linked_Server_Name , 'select * from TableName where ID = 500')
For what it's worth, I found the following syntax to work the best:
SELECT * FROM [LINKED_SERVER]...[TABLE]
I couldn't get the recommendations of others to work, using the database name. Additionally, this data source has no schema.
In sql-server(local) there are two ways to query data from a linked server(remote).
Distributed query (four part notation):
Might not work with all remote servers. If your remote server is MySQL then distributed query will not work.
Filters and joins might not work efficiently. If you have a simple query with WHERE clause, sql-server(local) might first fetch entire table from the remote server and then apply the WHERE clause locally. In case of large tables this is very inefficient since a lot of data will be moved from remote to local. However this is not always the case. If the local server has access to remote server's table statistics then it might be as efficient as using openquery More details
On the positive side T-SQL syntax will work.
SELECT * FROM [SERVER_NAME].[DATABASE_NAME].[SCHEMA_NAME].[TABLE_NAME]
OPENQUERY
This is basically a pass-through. The query is fully processed on the remote server thus will make use of index or any optimization on the remote server. Effectively reducing the amount of data transferred from the remote to local sql-server.
Minor drawback of this approach is that T-SQL syntax will not work if the remote server is anything other than sql-server.
SELECT * FROM OPENQUERY([SERVER_NAME], 'SELECT * FROM DATABASE_NAME.SCHEMA_NAME.TABLENAME')
Overall OPENQUERY seems like a much better option to use in majority of the cases.
I have done to find out the data type in the table at link_server using openquery and the results were successful.
SELECT * FROM OPENQUERY (LINKSERVERNAME, '
SELECT DATA_TYPE, COLUMN_NAME
FROM [DATABASENAME].INFORMATION_SCHEMA.COLUMNS
WHERE
TABLE_NAME =''TABLENAME''
')
Its work for me
Following Query is work best.
Try this Query:
SELECT * FROM OPENQUERY([LINKED_SERVER_NAME], 'SELECT * FROM [DATABASE_NAME].[SCHEMA].[TABLE_NAME]')
It Very helps to link MySQL to MS SQL
PostgreSQL:
You must provide a database name in the Data Source DSN.
Run Management Studio as Administrator
You must omit the DBName from the query:
SELECT * FROM OPENQUERY([LinkedServer], 'select * from schema."tablename"')
For MariaDB (and so probably MySQL), attempting to specify the schema using the three-dot syntax did not work, resulting in the error "invalid use of schema or catalog". The following solution worked:
In SSMS, go to Server Objects > Linked Servers > Providers > MSDASQL
Ensure that "Dynamic parameter", "Level zero only", and "Allow inprocess" are all checked
You can then query any schema and table using the following syntax:
SELECT TOP 10 *
FROM LinkedServerName...[SchemaName.TableName]
Source: SELECT * FROM MySQL Linked Server using SQL Server without OpenQuery
Have you tried adding " around the first name?
like:
select foo.id
from "databaseserver1".db1.table1 foo,
"databaseserver2".db1.table1 bar
where foo.name=bar.name

How can I use two different databases with Linq to SQL in Linqpad?

I'm starting out with Linq To SQL, fiddling around with Linqpad and I'm trying to duplicate a SQL script which joins on tables in separate databases on the same server (SQL Server 2008).
The TSQL query looks approximately like this:
using MainDatabase
go
insert Event_Type(code, description)
select distinct t1.code_id, t2.desc
from OtherDatabase..codes t1
left join OtherDatabase..lookup t2 on t1.key_id = t2.key_id and t2.category = 'Action 7'
where t2.desc is not null
I'm basically trying to figure out how to do a cross-database insertion. Is this possible with Linq To SQL (and is it possible in Linqpad?)
This is possible in LINQ to SQL if you create a (single) typed DataContext that contains table classes for objects in both databases. This designer won't help you here, so you have to create some of the table classes manually. In other words, use the VS designer to create a typed DataContext for your primary database, then manually add classes for the tables in the other database that you wish to access:
[Table (Name = "OtherDatabase.dbo.lookup")]
public class Lookup
{
...
}
Edit: In LINQPad Premium edition, you can now do cross-database queries with SQL Server - in one of two ways.
The simplest is the drag-and-drop approach: hold down the Ctrl key while dragging additional databases from the Schema Explorer to the query editor. To access those additional databases in your queries, use database.table notation, e.g., Northwind.Regions.Take(100). The databases that you query must reside on the same server.
The second approach is to list the extra database(s) that you want to query in the connection properties dialog. This dialog also lets you choose databases from linked servers. Here's how to proceed:
Add a new LINQ to SQL connection.
Choose Specify New or Existing Database and choose the primary database that you want to query.
Click the Include Additional Databases checkbox and pick the extra database(s) you want to include. You can also choose databases from linked servers in this dialog.
You can now do cross-database queries. These are properly optimized insofar as joins will occur on the server rather than the client.
Use linked servers with fully qualified names to query another database from the current DB. That should work.
using MainDatabase
go
insert Event_Type(code, description)
select distinct t1.code_id, t2.desc
from <Linked_Server>.OtherDatabase..codes t1
left join <Linked_Server>.OtherDatabase..lookup t2 on t1.key_id = t2.key_id and t2.category = 'Action 7'
where t2.desc is not null

How to make a select query for sql and access databases?

Using SQL server 2000 and Access 2003
Access Database Name - History.mdb
Access Table Name - Events
SQL Database Name - Star.mdf
SQL Table Name - Person
I want to take the field from person table, and include in Events table by using inner join
Tried Query
Select * from Events inner join person where events.id = person.id
So How to make a query for access and sql databases.
I want to make a Select query in access only. Not an sql Database.
Need Query Help?
While you can (possible, should -- why?) use a linked table, there are as ever more than one way to skin a cat. Here's another approach: put the connection details into the query test e.g. something like
SELECT *
FROM [ODBC;Driver={SQL Server};SERVER=MyServer;DATABASE=Star;UID=MyUsername;Pwd=MyPassword;].Person AS P1
INNER JOIN
[MS Access;DATABASE=C:\History;].[Events] AS E1
ON S1.seq = S2.seq
WHERE E1.id = P1.id;
You can set up a linked table in Access to your SQL Server, and the instructions on how to do so vary slightly in Access versions. Look in the help file for "Linked Table", or go here if you have Access 2007.
Once you have a linked table set up, you'll be able to access the SQL Server table in your query. Note that optimizing a linked table join takes some work.
You can create a linked table in Access, that points to the table in SQL. The rest you can achieve in the query designer.
You should add the msaccess db as a remote server.
then you can do that join

Resources