I am creating a SQL script that will check weather the object is there or not and then do create or alter based on that.
if not exists (select * from sysobjects where name='MyTableName' and xtype='U')
create table MyTableName(
Id int not null,
Name varchar(150) not null
)
Else
--Alter
Now having to do this for a bigger database which has more than 150 table.
Is there any way I can generate this automatically for tables and stored procedures?
As far as I can judge: Your question already includes the anser - NO it can not be done! The Thing is this: you COULD spool the metadata of tables etc. IF the objects existed in an Environment... as you arleady mentioned this is not the case - so how should a function / script / procedure be able to KNOW which columns etc. have to be created for which Table? Or what has to be altered if the table already existed?
Related
I am creating procedure for creating temporary table's but I want to make this more general instead of for just one original table's temporary
ALTER PROCEDURE [dbo].[CREATE_TEMP_TABLES]
AS
IF NOT EXISTS (SELECT * FROM SYS.TABLES
WHERE NAME=N'TEMP_FactAdditional' AND type ='U')
BEGIN
CREATE TABLE dbo.TEMP_FactAdditional
(
[ProductKey] [int] NOT NULL,
[CultureName] [nvarchar](50) NOT NULL,
[ProductDescription] [nvarchar](max) NOT NULL
)
END
GO
so IF NOT EXISTS (SELECT * FROM SYS.TABLES WHERE NAME=N'TEMP_FactAdditional' AND type ='U') in here I see its only creating TEMP_FactAdditional table and I have like 8 or 9 original tables which each of them is different, CREATE TABLE dbo.TEMP_FactAdditional I am thinking to add some function or method to make more general but I don't have that much knowledge about it, I am designing warehouse, and my first step is to make more efficient to transfer data's from DB to DB. such as here in the photo . Can someone help me to make procedure more efficient?
Well, I am not going to comment on the overall approach, but if you want a general way to create tables to move data into, you could do something like this....
SELECT *
INTO my_new_table_name
FROM my_old_table_name
WHERE 1 = 0
This will create the new table with the same structure and no data. Then you could theoretically write the procedure to use dynamic SQL to run this code for a list of tables, thus "creating" a number of tables in an abstract case. You could pass in two parameters, the two table names.
Is there any possibility to disable auto creating statistics on specific table in database, without disabling auto creating statistics for entire database?
I have a procedure wich written as follow
create proc
as
create table #someTempTable(many columns, more than 100)
inserting into #someTempTable **always one or two row**
exec proc1
exec proc2
etc.
proc1, proc2 .. coontains many selects and updates like this:
select ..
from #someTempTable t
join someOrdinaryTable t2 on ...
update #someTempTable set col1 = somevalue
Profiler shows that before each select server starts collecting stats in #someTempTable, and it takes more than quarter of entire execution of proc. Proc is using in OLPT processing and should works very fast. I want to change this temporary table to table variable(because for table variables server doesn't collect stats) but can't because it lead me to rewrite all this procedures to passing variables between them and all of this legacy code should be retests. I'm searching alternative way how to force server to behave temporary table like table variables in part of collecting stats.
P.S. I'm know that stats is useful thing but in this case it's useless because table alway contains small amount of records.
I assume you know what you are doing. Disabling a statistics is generally a bad idea. Anyhow:
EXEC sp_autostats 'table_name', 'OFF'
More documentation here: https://msdn.microsoft.com/en-us/library/ms188775.aspx.
Edit: OP clarified that he wants to disable statistics for a temp table. Try this:
CREATE TABLE #someTempTable
(
ID int PRIMARY KEY WITH (STATISTICS_NORECOMPUTE = ON),
...other columns...
)
If you don't have a primary key already, use an identity column for a PK.
I have a SQL Server Database Project in which I've made several changes to the schema where I've changed column data types from NUMERIC (18,0) to INT. We're trying to normalize the data type used for Primary Keys, it's a currently 50/50 mix.
When I generate the Publish script, some of the tables are recreated in the script:
CREATE TABLE [dbo].[tmp_XYZ]
INSERT TABLE [dbo].[tmp_XYZ] SELECT ... FROM [dbo].[XYZ]
DROP TABLE [dbo].[XYZ]
sp_rename N'[dbo].[tmp_XYZ]', N'XYZ';
but other tables are just updated via ALTER statements
ALTER TABLE [dbo].[ABC] ALTER COLUMN [AbcID] INT NULL;
Is there some rule that dictates when a table will be recreated, and when it's just altered in place ?
Probably the best way is to Right Click on your object name and choose script as ...
Then you have options to create or alter
If you couldn't find Alter ,you can go to design view, right click and choose Generate Change Script ... to find the alter statement.
This is just an easy problem. It's the same problem as changing a table in the table designer. I think you've changed a column inside your table design which needs to drop and recreate the table to let the column order in the same position.
Here is a short example. Take this table design as given:
CREATE TABLE dbo.Test(
id int identity(1,1),
firstname nvarchar(100),
name nvarchar(100),
street nvarchar(100)
)
This will create the columns in a specified order. You can see this order here:
SELECT name, column_id
FROM sys.columns
WHERE object_id = OBJECT_ID(N'dbo.Test')
You'll see something like that:
column_name column_id
id 1
firstname 2
name 3
street 4
If you change the the column name via designer or in your case in the data project, this will cause SQL Server to obtain this order upright.
In this case you try to change the column name to lastname. This will enforce SQL Management Studio and other programs like that to keep the column_id upright. This can only be done, if the table is completely recreated with the right columnorder. SQL Server create a temporary table stub, insert everything into it, drop the old table and rename the temporary table to the old original name. Just as in your code above.
After that you'll see something like that:
column_name column_id
id 1
firstname 2
lastname 3
street 4
If you would simply rename the last column or do it manually, everything would be fine. Manually would be much more efficient, as there isn't the need to move ALL data to a new table. The manual way would be this:
-- Create the new column
ALTER TABLE dbo.Test ADD lastname nvarchar(100)
GO
-- Populate the new column using the old one
UPDATE dbo.Test
SET lastname = name
GO
-- Drop the old column afterwards
ALTER TABLE dbo.Test DROP COLUMN name
This behavior will result in the following result:
column_name column_id
id 1
firstname 2
street 4
lastname 5
The last one will be much more efficient, as already stated.
Hopefully this will answer your question, even if the answer comes lately.
Is it possible to add a column to a table at a specific ordinal position in Microsoft SQL Server?
For instance, our tables always have CreatedOn, CreatedBy, LastModifiedOn, LastModifiedBy columns at the "end" of each table definition? I'd like the new column to show up in SSMS above these columns.
If I am scripting all my database changes, is there a way to preserve this order at the end of the table?
FYI, I'm not trying to institute a flame war on if this should even be done. If you want to read about a thread that degenerates quickly into that, here's a good one:
http://www.developersdex.com/sql/message.asp?p=581&r=5014513
You have to create a temp table that mirrors the original table's schema but with the column order that you want, then copy the contents of the original to temp. Delete the original and rename the temp.
This is what SQL Management Studio does behind the scenes.
With a schema sync tool, you can generate these scripts automatically.
go into SQL Server management Studio, and "design" an existing table. Insert a column in the middle, right click in an empty area and select Generate Change Script...
Now look at the script it creates. it will basically create a temp table with the proper column order, insert the data from the original table, drop the original table, and rename the temp table. This is probably what you'll need to do.
You may also need to uncheck this option to allow creation of change scripts
The answer is yes, it is technically possible, but you will have a headache doing so and it will take a long time to execute and set up.
One: Create/Copy/Drop/Rename
This is actually what SQL Server is doing in the graphical interface: here's an example of the script it is generating and executing when you click the 'save' button after adding a new column to the beginning of a table.
/* To prevent any potential data loss issues, you should review this script in detail before running it outside the context of the database designer.*/
BEGIN TRANSACTION
SET QUOTED_IDENTIFIER ON
SET ARITHABORT ON
SET NUMERIC_ROUNDABORT OFF
SET CONCAT_NULL_YIELDS_NULL ON
SET ANSI_NULLS ON
SET ANSI_PADDING ON
SET ANSI_WARNINGS ON
COMMIT
BEGIN TRANSACTION
GO
CREATE TABLE dbo.Tmp_SomeTable
(
MyNewColumn int NOT NULL,
OriginalIntColumn int NULL,
OriginalVarcharColumn varchar(100) NULL
) ON [PRIMARY]
TEXTIMAGE_ON [PRIMARY]
GO
ALTER TABLE dbo.Tmp_SomeTable SET (LOCK_ESCALATION = TABLE)
GO
SET IDENTITY_INSERT dbo.Tmp_SomeTable ON
GO
IF EXISTS(SELECT * FROM dbo.SomeTable)
EXEC('INSERT INTO dbo.Tmp_SomeTable (OriginalIntColumn, OriginalVarcharColumn FROM dbo.SomeTable WITH (HOLDLOCK TABLOCKX)')
GO
SET IDENTITY_INSERT dbo.Tmp_SomeTable OFF
GO
DROP TABLE dbo.SomeTable
GO
EXECUTE sp_rename N'dbo.Tmp_SomeTable', N'SomeTable', 'OBJECT'
GO
GO
COMMIT
Two: ADD COLUMN / UPDATE / DROP COLUMN / RENAME
This method basically involves creating a copy of any existing columns that you want to add to the 'right' of your new column, transferring the data to the new column, then dropping the originals and renaming the new ones. This will play havoc with any indexes or constraints you have, since you have to repoint them. It's technically possible, but again time-consuming both in terms of development and execution.
CREATE TABLE MyTest (a int, b int, d int, e int)
INSERT INTO MyTest (a,b,d,e) VALUES(1,2,4,5)
SELECT * FROM MyTest -- your current table
ALTER TABLE MyTest ADD c int -- add a new column
ALTER TABLE MyTest ADD d_new int -- create copies of the existing columns you want to move
ALTER TABLE MyTest ADD e_new int
UPDATE MyTest SET d_new = d, e_new = e -- transfer data to the new columns
ALTER TABLE MyTest DROP COLUMN d -- remove the originals
ALTER TABLE MyTest DROP COLUMN e
EXEC SP_RENAME 'MyTest.d_new', 'd'; -- rename the new columns
EXEC SP_RENAME 'MyTest.e_new', 'e';
SELECT * FROM MyTest
DROP TABLE MyTest -- clean up the sample
Three: Live with it
This mightily offends my sense of order ... but sometimes, it just isn't worth reshuffling.
To my knowledge there is no known method to change the order of the column. Behind the scenes SQL Management Studio does what Jose Basilio said. And if you have a big table then it is impractical to change the column orders like this way.
You can use a "view". With SQL views you can use any order you like without getting affected by the table column changes.
I am using SSMS 18. I did in simple way
Opened design of table
positioning the required column by dragging it
And as per the answer from KM (second in thread) - uncheck the option to allow creation of change scripts refer image above.
Save the changes.
Done. Check your table now.
TFS 2013 will do this for you automatically.
Add the new column(s) to your table anyway you like, and then commit your changes to TFS. From there you can open the table's sql file in Visual Studio and manually move the order of the columns in the T-SQL CREATE script. Then you can update your target database by using VS's schema compare tool found under Tools > SQL Server > New Schema Comparison. Choose your Database project with your change as the source, and the database you want to update as the target. Compare, select the table's script, and Update. VS will drop and add automatically. All your data will be safe, and indexes too.
What i think is simple is to add the column ALTER TABLE table1 ADD .. and then create a tmp table like tmp_table1 from the select like
SELECT col1,col2,col5,col3,col4 into tmp_table1 from table1;
and then drop table1 and rename the tmp_table1 to table1, that is it. I hope it will help someone
Select all the columns into a temp table, and create a new table with the new column you want. Then drop the old table, select all the columns from the temp table, and insert them into the new table with the reordered column. No data is lost.
SELECT * FROM TEMP
SELECT * FROM originaltbl
SELECT * FROM #Stagintbl
DECLARE #ColumnName nvarchar(max);
SET #ColumnName=(SELECT
DISTINCT STUFF((
SELECT ',' + a.COLUMN_NAME
FROM (
SELECT Column_name
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME='originaltbl') a
for xml path('')
),1,1,'') AS ColumnName)
DECLARE #Sqlquery nvarchar(max)
SET #Sqlquery = 'SELECT ' + #ColumnName + ' FROM #Stagintbl' + '';
INSERT INTO originaltbl
EXECUTE(#Sqlquery)
Dirty and simple.
Export table to csv.
Insert new data at desired position.
Drop table.
Create new table with desired column specifications.
Load columns from csv to new table.
I am not sure if the thread is still active. I was having the same query with MySQL database. Right clicking the table and selecting 'ALTER' auto generated the below code. Sample provided from sakila db and it worked. Just find out the column after which you want to place your new column and use 'AFTER' keyword
ALTER TABLE `sakila`.`actor`
CHANGE COLUMN `middle_name` `middle_name` VARCHAR(50) NULL DEFAULT NULL AFTER `first_name`;
In SQL Server (in my case, 2005) how can I add the identity property to an existing table column using T-SQL?
Something like:
alter table tblFoo
alter column bar identity(1,1)
I don't beleive you can do that. Your best bet is to create a new identity column and copy the data over using an identity insert command (if you indeed want to keep the old values).
Here is a decent article describing the process in detail:
http://www.mssqltips.com/tip.asp?tip=1397
The solution posted by Vikash doesn't work; it produces an "Incorrect syntax" error in SQL Management Studio (2005, as the OP specified). The fact that the "Compact Edition" of SQL Server supports this kind of operation is just a shortcut, because the real process is more like what Robert & JohnFX said--creating a duplicate table, populating the data, renaming the original & new tables appropriately.
If you want to keep the values that already exist in the field that needs to be an identity, you could do something like this:
CREATE TABLE tname2 (etc.)
INSERT INTO tname2 FROM tname1
DROP TABLE tname1
CREATE TABLE tname1 (with IDENTITY specified)
SET IDENTITY_INSERT tname1 ON
INSERT INTO tname1 FROM tname2
SET IDENTITY_INSERT tname1 OFF
DROP tname2
Of course, dropping and re-creating a table (tname1) that is used by live code is NOT recommended! :)
Is the table populated? If not drop and recreate the table.
If it is populated what values already exist in the column? If they are values you don't want to keep.
Create a new table as you desire it, load the records from your old table into your new talbe and let the database populate the identity column as normal. Rename your original table and rename the new one to the correct name :).
Finally if the column you wish to make identity currently contains primary key values and is being referenced already by other tables you will need to totally re think if you're sure this is what you want to do :)
There is no direct way of doing this except:
A) through SQL i.e.:
-- make sure you have the correct CREATE TABLE script ready with IDENTITY
SELECT * INTO abcTable_copy FROM abcTable
DROP TABLE abcTable
CREATE TABLE abcTable -- this time with the IDENTITY column
SET IDENTITY_INSERT abcTable ON
INSERT INTO abcTable (..specify all columns!) FROM (..specify all columns!) abcTable_copy
SET INDENTITY_INSERT abcTable OFF
DROP TABLE abcTable_copy
-- I would suggest to verify the contents of both tables
-- before dropping the copy table
B) Through MSSMS which will do exactly the same in the background but will less fat-fingering.
In the MSSMS Object Explorer right click the table you need to modify
Select "design" Select the column you'd like to add IDENTITY to
Change the identity setting from NO -> YES (possibly seed)
Ctr+S the table
This will drop and recreate the table with all original data in it.
If you get a warning:
Go to MSSMS Tools -> Options -> Designers -> Table and database Designers
and uncheck the option "Prevent saving changes that require table re-creation"
Things to be careful about:
your DB has enough disk space before you do this
the DB is not in use (especially the table you are changing)
make sure to backup your DB before doing it
if the table has a lot of data (over 1G) try it somewhere else first
before using in real DB
Create a New Table
SELECT * INTO Table_New FROM Table_Current WHERE 1 = 0;
Drop Column from New Table
Alter table Table_New drop column id;
Add column with identity
Alter table Table_New add id int primary key identity;
Get All Data in New Table
SET IDENTITY_INSERT Table_New ON;
INSERT INTO Table_New (id, Name,CreatedDate,Modified)
SELECT id, Name,CreatedDate,Modified FROM Table_Current;
SET IDENTITY_INSERT Table_New OFF;
Drop old Table
drop table Table_Current;
Rename New Table as old One
EXEC sp_rename 'Table_New', 'Table_Current';
alter table tablename
alter column columnname
add Identity(100,1)