Create a SQL Server CREATE TABLE statement using T-SQL - sql-server

The creation of a SQL Server External Table requires remote tables to be made accessible by running code of the following format on the local database:
CREATE EXTERNAL TABLE [TABLE_NAME]
(
[Id] [int] NOT NULL,
[Name] [int] NULL,
)
WITH (DATA_SOURCE = [EXTERNAL_DB_NAME])
I have a quite a few external tables to work with, and am wondering if this functionality can be automated. So, is there a way to create the text for a CREATE TABLE statement from the Information Schema views on the remote database ? This could then be altered and used to populate a dynamic query to be run on the local database.

Related

Azure cross database queries,External resources, External tables

I am migrating all my VM Sql Server 2012 database to Azure Sql Database. In my current structure I am using cross database queries to fetch data from different database tables.
I have created external table to my parent table using below query
CREATE MASTER KEY ENCRYPTION BY PASSWORD = 'yourPassword';
CREATE DATABASE SCOPED CREDENTIAL yourServeradminlogin
WITH IDENTITY = 'yourServeradminlogin',
SECRET = 'yourPassword';
CREATE EXTERNAL DATA SOURCE RefmyDemoDB2
WITH
(
TYPE=RDBMS,
LOCATION='testdbdemoserver.database.windows.net',
DATABASE_NAME='myDemoDB2',
CREDENTIAL= yourServeradminlogin
);
CREATE EXTERNAL TABLE [dbo].[Department](
[DeptId] [int] NOT NULL,
[Name] [varchar](50) NULL
)
WITH
(
DATA_SOURCE = RefmyDemoDB2
);
/****** Script for SelectTopNRows command from SSMS ******/
SELECT *
FROM [dbo].[Employee] E
INNER JOIN [dbo].[Department] D
ON E.DeptId = D.DeptId
I referred this link https://www.c-sharpcorner.com/article/cross-database-queries-in-azure-sql/
But when I create external table it doesn't shows table in external table folder like shown in below image.
In my case it directly showing in Tables folder.
Anyone knows why I don't see Department table in External Tables folder? How can I add such tables in External Tables folder?
External tables are available in Azure SQL only to support a feature called "Elastic Queries", that may solve your problem:
https://learn.microsoft.com/en-us/azure/sql-database/sql-database-elastic-query-overview
If this is not enough for you, and you really need full cross-database query support, you have to use an Azure SQL Managed Instance:
https://learn.microsoft.com/en-us/azure/sql-database/sql-database-managed-instance
which seems to be exactly what you need.

Can I get a table script with its data

I am using a SQL Server 2008 database.
I have two databases namely db1 and db2. In both there is a table tblcountry. I create this on 1st database. Then how can I script with its data for create on 2nd database?
I use the code below
CREATE TABLE [dbo].[tblCountry]
(
[record_Id] [int] IDENTITY(1,1) NOT NULL,
[country] [nvarchar](150) NULL,
[nationality] [nvarchar](150) NULL,
[lsdMdfdOn] [datetime] NULL,
[lstMdfdBy] [nvarchar](350) NULL,
[isDeleted] [bit] NULL,
[isEnabled] [bit] NULL,
)
Then what code will I use for the getting include the data?
No, you cannot view the data if you are using the create query.
If you want to see the data of the table on second database then you can use this query on your second database db2
select * from [db1].[dbo].[tblCountry]
But you can not view the data and create query at the same time.
Although it may seem very wierd solution but I guess what you can do is you can copy the create query on the query analyzer window and beneath that write the select query and execute it. (But I guess this is how most of the programmers do that)
If you are on the same server or have a linked server:
CREATE TABLE tblCountry
SET IDENTITY_INSERT tblCountry ON
INSERT INTO [database2].tblCountry
SELECT * FROM [database1].tblCountry
SET IDENTITY_INSERT tblCountry OFF
The most Easy way for this problem is for you to
Right Click on the Database on the Object Explorer
click Generate Scripts
on the introduction click Next
Select radio button on Script entire database and all database
objects or you can just select specific tables or stored
procedures by selecting the other radio button
On the Set Scripting Options click on Advanced Select the things you
want to script
Then on the Query just change the database name after the query USE
db2
Right click on database and click on tasks and export data
you can use export data option in sql server...it will give you data with table script

Create Table in Access with identity value

I want to make a query in witch it creates a simple table, In SQL that would be:
CREATE TABLE RealInventry (ID int IDENTITY(1,1) NOT NULL,PartNumber varchar(255),QTY varchar(255),Locator varchar(255))
I'm trying to do the same it Access DB, but I'm getting an error in "IDENTITY" syntax. How can I make this SQL query work on Access, I'm currently using Access 2013
Any help is appreciated.
Try Autoincrement instead of Identity:
CREATE TABLE test (ID AUTOINCREMENT NOT NULL,PartNumber varchar(255),QTY varchar(255),Locator varchar(255))

SQL Server automatic naming of indexes when creating tables

I'm rather new to SQL Server, (did learn SQL back in late 1980's, DB2 if I recall) Today I'm integrating my database layer into SQL, to begin with, SQL Server.
To begin with. As I do today, I will generate in runtime every databases objects, tables objects and indexes programmatically as I do with almost every visual and data object in my projects. That is, I use the visual designing tools very limited.
Every column in my project has a external description file's (every user has profile which contains these files), just as I do with database key's and for visual objects as for effect's as positioning, length, picture-mask, font size, etc. etc. i.e. dynamic forms. Almost every window, grids, filters is created in runtime just as far most of my database connections.
I did build a small test "machine" to create tables in this environment and did well, very easy to create tables within program (I use delphi and ADO)
The problem I encounter is when I flag a column as "autoincrement" or as Identity in SQL Server or if I describe a column as primary key, then SQL Server Management Studio creates automatically a index or key.
That would be ok if I could manage the name it gives this index or key.
Example of this situations:
AdoCommand.CommandText := Str_SQL;
TRY
AdoCommand.Execute;
FINALLY
NotiFy_TimeOut ('Table was created', wait_for_one_sec);
END;
My database engine creates this SQL script which I pass into the string Str_SQL above:
CREATE TABLE GENGITFL
(
NR INT NOT NULL IDENTITY,
GJM CHAR(3) NOT NULL,
HEITI VARCHAR(25) NOT NULL,
KAUPG REAL NULL,
SOLUG REAL NULL,
TOLLG REAL NULL,
DUMMY VARCHAR(20) NULL,
UNIQUE (GJM),
PRIMARY KEY (GJM)
)
SQL Server creates these two indexes automatically :
PK__GENGITFL__C51F17260A463F49
UQ__GENGITFL__C51F17277FA3E6E6
I don't want to use these names for these files, I would prefer names as:
IDX_GENGITFL_GJM
IDX_GENGITFL_NR
The reason should be obvious in light of my intro, the runtime engine can't create these names automatically and I consider it not a option to look for what index files are available within system database. If my external description say there should be index, I would like just to create names for the index automatically by using the prefix, IDX_ next the table name and last the field name or name's with underscore between, as IDX_GENGITFL_GJM etc.
Hope someone understand my poor english and presentation.. I'm rather rusty in english.
Thanks
Edit: After help from marc_s my SQL "script" is like this:
CREATE TABLE GENGITFL
(
NR INT NOT NULL IDENTITY,
GJM CHAR(3) NOT NULL,
HEITI VARCHAR(25) NOT NULL,
KAUPG REAL NULL,
SOLUG REAL NULL,
TOLLG REAL NULL,
DUMMY VARCHAR(20) NULL,
CONSTRAINT IDX_GENGITFL_NR UNIQUE (NR),
CONSTRAINT IDX_GENGITFL_GJM PRIMARY KEY (GJM),
)
CREATE INDEX IDX_GENGITFL_HEITI ON GENGITFL (HEITI)
Thanks again.
If you don't want the system default names - then just specify your own! :
CREATE TABLE GENGITFL
(
NR INT NOT NULL IDENTITY,
GJM CHAR(3) NOT NULL,
HEITI VARCHAR(25) NOT NULL,
KAUPG REAL NULL,
SOLUG REAL NULL,
TOLLG REAL NULL,
DUMMY VARCHAR(20) NULL,
CONSTRAINT IDX_GENGITFL_NR UNIQUE (GJM),
CONSTRAINT IDX_GENGITFL_GJM PRIMARY KEY (GJM)
)
See those CONSTRAINT (yourownnamehere) before the UNIQUE and the PRIMARY KEY ?
Now, your constraints are named as you defined.

SQL Management Studio "Table -> Script CREATE" creates ALTERs

When I try to script a table CREATE from a database, it doesn't always script all the columns inside a single CREATE TABLE. Some of the columns will be added via ALTER TABLEs. Why is this? Is SQL server capturing the history of the schema modifications, and any columns added after the initial creation are scripted with ALTERS? The reason this matters is because I'm scripting tables to be used within a VS Database project and it can't handle the ALTER statements.
CREATE TABLE [dbo].[tblPackageType]
(
[PackageTypeId] [int] IDENTITY(1,1) NOT FOR REPLICATION NOT NULL,
[PackageTypeDesc] [varchar](50) NOT NULL
) ON [PRIMARY]
ALTER TABLE [dbo].[tblPackageType] ADD [EDIcode] [varchar](10) NOT NULL
ALTER TABLE [dbo].[tblPackageType] ADD [EDI211] [varchar](10) NULL
Is SQL server capturing the history of the schema modifications, and any columns added after the initial creation are scripted with ALTERS?
Yes.
If you want to get around this, you can alter the script to be a create including all the needed columns, and after you run it the updated definition will be saved.

Resources