How do I create tables from my .sql file in SQL Server - sql

How do I create a table in SQL Server from a .sql? I see the query statements and the data to be inserted into the table but how do I create the actual tables?

If the statements to create the tables aren't in the .sql file, then you will need to know their structure and create them, either by using a handwritten query, another .sql file or SQL Server Management Studio (SSMS).
In SSMS you can expand a database in the Object Explorer and then right click on "Tables" to select "New Table..." then you will get a UI for defining the columns you need.
With the context of your previous question you need to contact whoever supplied the .sql files and ask for a script to create the required tables. Or perhaps they should send you a copy(a backup) of the database.

You can run it from the command prompt using the command below:
sqlcmd -S myServer\instanceName -i C:\myScript.sql
http://msdn.microsoft.com/en-us/library/ms170572.aspx
This assumes that your .sql files contains the logic to create the needed tables.

You can create tables from a sql script like so.
CREATE TABLE MyTable1 (
MyString1 NVARCHAR(50) NOT NULL,
MyInt1 INT NULL NULL
)
GO
CREATE TABLE MyTable2 (
Id INT IDENTITY(1,1) NOT NULL,
Name NVARCHAR(50) NOT NULL,
PRIMARY KEY(Id)
)
GO
See http://msdn.microsoft.com/en-US/library/ms174979%28v=SQL.90%29.aspx for more info

Related

How to generate the script of rename table using sqlpackage.exe?

I have Two Database some-db-dev & some-db-qa. Both the databases are identical to each other.
I have created a DACPAC File for both the databases. some-db-dev.dacpac and some-db-qa.dacpac respectively.(It had the Table as "A" and Column "Test" in it. It also had some dummy records in it.)
After this I have performed below steps:
Renamed the Table "A" to "ARenamed" from some-db-dev Database.
Generated the DACPAC of "some-db-dev" and Stored it with the name "some-db-dev"
I have fire below command :-
sqlpackage /a:Script /sf:"C:\Users\some.user\Desktop\some-db-dev.dacpac" /tf:"C:\Users\some.user\Desktop\some-db-qa.dacpac" /tdn:"some-db-qa" /op:"C:\Users\some.user\Desktop\diffscript.sql"
Observations :-
Instead of renaming the Table modified at Step 1. It generated the Script of creating the table as below.
`GO
PRINT N'Creating [dbo].[ARenamed]...';
GO
CREATE TABLE [dbo].[ARenamed] (
[Id] NCHAR (10) NULL,
[Name] NCHAR (10) NULL,
[Test] NCHAR (10) NULL
);`
Is there something wrong with the command that I am using ??
Any help will be appreciable.
To rename a table in SSDT you need to use the refactoring tools "right click on the table and do refactor-rename". What happens is this adds an entry to the "RefactorLog.xml" - if you have one of those then when a deployment is created an sp_rename is generated, other you will get what you see here a drop and then create.
See: https://the.agilesql.club/2016/09/refactoring-in-sql-server-data-tools-ssdt/
The last section "Renaming Objects" shows how to do it.
Ed
I think that you'll need to use MSBuild instead. That's an example how to generate script project vs database.
MsBuild.exe "PATH_TO_SQL_PROJ_FILE" ^
/p:SqlPublishProfilePath="PATH_TO_PUBLISH_PROFILE" ^
/p:UpdateDatabase=False ^
/t:Build,Publish

generate scripts in sql server be generated as a StoredProcedure or written to a text file

I am aware of SQL server being able to generate scripts about metadata of tables in a database. I was wondering if there is a way to do this without using the wizard. Whether it can be done using a Stored Procedure to write to a txt file or using SSIS to generate the DDL commands. I just want something so I can a job automatically overnight, so there no manual intervention running the wizard. if there is a way of doing this on SQL server Management studios using commands or SSIS.
Thank you
you could setup a database trigger that keeps record of any change in your development database.
An example is this :
create TRIGGER trDDLHistory ON DATABASE
for CREATE_FUNCTION, ALTER_FUNCTION, DROP_FUNCTION,
CREATE_PROCEDURE, ALTER_PROCEDURE, DROP_PROCEDURE,
CREATE_TABLE, ALTER_TABLE, DROP_TABLE,
CREATE_TRIGGER, ALTER_TRIGGER, DROP_TRIGGER,
CREATE_VIEW, ALTER_VIEW, DROP_VIEW
-- there are more offcourse..
AS
BEGIN
INSERT INTO tblDDLHistory(DDLHistory)
VALUES(convert(nvarchar(max), EVENTDATA()))
END;
example of tblDDLHistory is
CREATE TABLE [dbo].[tblDDLHistory] (
[DDLHistoryID] INT IDENTITY(1,1) NOT NULL,
[DDLDate] DATETIME NOT NULL DEFAULT (getdate()),
[DDLHistory] XML NULL,
CONSTRAINT [PK_DDLHistoryID] PRIMARY KEY (DDLHistoryID)
)
Now you can get all changes from here to use in your production database.

How to use SQL Server Temporary table #tblTmpYaks in Microsoft Access VBA?

I need to create a local temporary table #tblTmpYaks, then select records in this temp table to show in a PassThrough Query.
The temporary table is created as this:
CREATE TABLE #tblTmpYaks (ID INT NOT NULL IDENTITY,
YakName CHAR(30),
PRIMARY KEY (ID));
INSERT INTO #tblTmpYaks (YakName) VALUES('My Yak');
INSERT INTO #tblTmpYaks (YakName) VALUES('My Female Yak');
And then a passthru query is created with the SQL string:
SELECT * FROM #tblTmpYaks;
But this does not work, as show the MsgBox when I open it:
That means that the #tblTmpYaks does no more exist in the SQL Server.
How to make this work ?
Conclusion added a Posteriori
As Gord Thompson states below, I abandon the use of local temporary table #tblTmpYaks that lives only during a local SQL Server Session. Instead, a Global temporary table is used here noted ##tblTmpYaks, it can be implied in the RecordSource of an Access report through a passthrough query, and more it will be automatically deleted when one quits the Access Interface.
In a similar fashion to the question here, you'll probably have better luck if you use a SQL Server global temporary table (##tblTmpYaks instead of #tblTmpYaks). If you create the table via a CREATE TABLE Pass-Through query in Access then the table should persist until you close Access (unless you explicitly DROP TABLE first).

sql script from base

in my project database model is changed periodically, but since database contains test data they have to re-enter each time.
script to insert data quickly becomes relevant. at the moment it is done manually. how this can be done using sql management studio?
I need a script with the data from the tables (to insert ready data to a new table), the script for the database model I have.
for example: i have table [dbo].[Users], table has 3 column [Id],[Login],[Email] and currency contain only one user(Id = 1, Login = 'Anton', Email = 'fake#mail.com')...i create script for my base and resul will be somthink like this
CREATE TABLE [dbo].[Users] (
[Id] int IDENTITY(1,1) NOT NULL,
[Login] decimal(1024) NOT NULL,
[Email] nvarchar(1024) NOT NULL,
);
INSERT INTO Users([Id],[Login],[Email]) VALUES(1, 'Anton', 'fake#mail.com')
There's actually a standalone official tool with which you can create schema and data dumps as sql scripts. Just follow the wizard and make sure you've set the checkbox to export data. As far as I know, it comes included into SQL Management Studio 2008 or later.

SQL script syntax for multiple databases under one user

This is probably stupid simple, but for some reason I'm having trouble getting it to work. I have a typical import script I'm trying to run on a MS SQL server with one master user (as opposed to a single user with only access to one database).
When I run the .SQL script, it creates the database and then starts to create tables. Here's where it gets interesting. It's not creating the databases under the DB I just made. It's throwing the tables under the "System Databases" view and not restricting the table creation to the DB that was just created.
I have tried:
CREATE TABLE table_name
CREATE TABLE database_name.table_name
Maybe I'm overlooking something really easy. I don't usually run into this with MySQL with a single user mapped to one database, I think since the user can only see that one database, so MySQL assumes it must be the one to work with.
The difference now is that I'm using MSSQL 2008 and maybe it works a little differently and I'm overlooking something. Thanks for your help!
Tried this too. No luck. Says database doesn't exist when it tries to create the table. I would think being a top/down read of the query script it would first create the database, then try to create the table afterwards.
CREATE DATABASE DATABASENAME;
CREATE TABLE DATABASENAME.dbo.TABLENAME
(
field_one VARCHAR(100) NOT NULL,
field_two INT NOT NULL,
PRIMARY KEY(field_one)
)
This is a working example after getting it all figured out. This syntax works well and I don't need to specify the DBO pathing stuff before table names this way. Cleaner and got me the results I was looking for. Thanks everyone.
IF Db_id('DBNAME') IS NULL
CREATE DATABASE DBNAME;
GO
USE [DBNAME];
GO
CREATE TABLE TABLENAME
(
COL1 VARCHAR(100) NOT NULL,
COL2 INT NOT NULL,
PRIMARY KEY(COL2)
)
INSERT INTO TABLENAME
(COL1,
COL2)
VALUES('1234',1001),
('1234',1002),
('1234',1003),
('1234',1004)
It basically just does a check to make sure database is created before doing anything else, then sets the USE database to the one I'm working with. Everything else is just normal SQL, so have fun. Cheers!
Probably you need to include the USE sentence at the begining of your script in order to indicate the database as follows:
USE [database_name]
GO
By default SQL-SERVER use the master DB that´s listed under system databases.
Other way is to use the database prefix, but including the owner:
INSERT INTO database_name.dbo.table_name
INSERT INTO database_name..table_name