Sql query for alter Table - sql-server

I'm trying to alter a table and add a column at position which is after an existing column,
but I can't make it since getting the following
error:
Msg 102, Level 15, State 1, Line 2 Incorrect syntax near 'AFTER'.
and the query I used is:
ALTER TABLE DealerGroup
ADD Status varchar(50)
AFTER Description;

Microsoft SQL Server does not support the after part, which I believe is specific to MySQL.
In any case the internal ordering of columns should not matter to you, unless you rely on getting an ordered result when doing select * which you shouldn't do anyway.

You can't add a column to a specific position in a table. Actually the RDBMS (SQL Server in this case) doesn't care where a column resides in the order of a table.
When you add another column to a table, it always goes "last".

You cannot add the column after specified column because in database structure column order doesn't matter when you need to fetch the data, and also AFTER is not any keyword defined in it in case of alter table query.
OR if you still want to, then you have to drop the table and re-create it with required column ordering.

Related

DROP all columns from an existing SQL Server table

I need to drop all columns in an existing table in SQL Server. It is possible to delete columns by specifying each column name. I want to delete every column without specifying column name. I am looking for something like
ALTER TABLE tblUser DROP COLUMN *;
Is there any known way to do this?
Answering your question literally, no you can't. If you try to remove the last column, SQL Server will throw the following error:
Msg 4923, Level 16, State 1, Line 12
ALTER TABLE DROP COLUMN failed because 'Id' is the only data column in table 'NoColumns'. A table must have at least one data column.
As such, if you actually want to solve your problem, whatever it is, it would be best to voice the initial problem and not the solution you decided to pursue.
Instead remove all the columns, you could drop the table
DROP TABLE TABLENAME
Or You can mention all the column names in Alter query
ALETR TABLE TableName DROP COLUMN Column1, Column2, Column3....ColumnN

SQL Server Computed Column that doesn't affect existing data

is that possible to do a computed column without affecting existing data?
I have a unique index column named
"BookingNo"
For newly insert Column I want it to be following this format
(format([CreationTime],'yyMMddHHmmssff'))
I tried used Computed Column but it modified all my existing data.
my existing BookingNo format was
201800123
Is there anyway to generate via database? Or we have insert via code?
You could just add a default constraint:
ALTER TABLE TableName
ADD CONSTRAINT DF_BookingNo DEFAULT(format(SYSDATETIME(),'yyMMddHHmmssff'))
FOR BookingNo
This way you will get the value only for newly created rows.
Please note that if this column has a unique constraint on it some inserts might fail if they are executed at the same time.

SQL Server 2012: ALTER TABLE ALTER COLUMN MyColumn1 fails because one or more objects access this column

I have a table which contains MyColumn1 with user defined datatype of CustomDatatype INT NOT NULL. I need to change this column to a VARCHAR(5), but I am getting the following errors:
Msg 5074, Level 16, State 1, Line 12
The object 'CustomDatatype' is dependent on column 'MyColumn1'.
Msg 4922, Level 16, State 9, Line 12
ALTER TABLE ALTER COLUMN MyColumn1 failed because one or more objects access this column.
This does not seem to be related to an index or foreign key reference which I would omit to drop before altering the column datatype, this seems to be directly related to the originally used custom defined datatype CustomDatatype on this column.
How can I change MyColumn1's datatype without dropping the CustomDatatype because that could create apocalyptic scenario in my system or dropping the table?
Thanks
Update (2018-07-31): I found a response to the same question in different forum where it states: "...This is the problem with UDT columns. You will need to drop all the columns of this type first in all tables (and may be in functions / SPs, views), then delete the type and create correct type, then re-create all the columns..." (Naomi 2011) from Microsoft (August 2, 2011) web: https://social.msdn.microsoft.com/Forums/sqlserver/en-US/b7bf0f04-dee8-4751-803b-4c3e1f7f7c70/how-to-change-column-nametype-of-user-defined-table-type?forum=transactsql
So far the only viable solutions I came up with are to:
Create a copy of the table (script it out with all
dependencies i.e.: triggers, indexes, keys, etc.) Drop the original
table (which is ok to do even though custom datatypes are specified) and then recreate the table again with the new datatype column.
If the table cannot be dropped (for some reason) rename the old
datatype column, create a new column with the original column name
with the right datatype. Move the data from the old (renamed) column
into the new one (make sure to mind the triggers,etc.). Then force
to recompile all the Sprocs and refresh all the views which are
dependent.
Can you check if there is any Index added for those column?
If yes,
you will need to drop and recreate the index.
once you drop the constraints and index , you can alter the column.
alter table Table1
alter column MyColumn1 varchar(5);
Then re-create constraints and index.
So far the only viable solutions I came up with are to:
1) Create a copy of the table (script it out with all dependencies i.e.: triggers, indexes, keys, etc.) Drop the original table (which is ok to do even though custom datatypes are specified) and then recreate the table again with the new datatype column.
2) If the table cannot be dropped (for some reason) rename the old datatype column, create a new column with the original column name with the right datatype. Move the data from the old (renamed) column into the new one (make sure to mind the triggers,etc.). Then force to recompile all the Sprocs and refresh all the views which are dependent.

Reducing data type size causes index to exceed maximum size?

Today I am facing a weird message. I am not sure if it is just a bug:
The tables are created by ASP.NET Identity. However, they are using nvarchar(450) for the Id, which, I cannot use in other tables because the index exceeds 900 bytes. Therefore I am trying to reduce it, but how could the PK_AspNetUserRoles be created in the first place? Is it just a SSMS bug?
What is your SSMS version?
IMHO, t's a bug, I cannot reproduce this issue in 12.0.4100.1.
You cannot change column type without recreating the index, so the error that you could receive might be:
Msg 5074, Level 16, State 1, Line 4
The index 'PK_AspNetUserRoles' is dependent on column 'UserId'.
Msg 4922, Level 16, State 9, Line 4
ALTER TABLE ALTER COLUMN UserId failed because one or more objects access this column.
But my SSMS just silently did the following:
create new table with the same name and tmp prefix having
nvarchar(150)-column
insert into new table select * from original table
drop original table
rename new table as old table
create index PK on it
No error was shown

Changing column constraint null/not null = rowguid replication error

I have a database running under Sql server 2005 with merge replication. I want to change some of the FK columns to be 'not null' as they should always have a value. SQL server won't let me do that though, this is what it says:
Unable to modify table. It is invalid to drop the default constraint
on the rowguid column that is used by
merge replication. The schema change
failed during execution of an internal
replication procedure. For corrective
action, see the other error messages
that accompany this error message. The
transaction ended in the trigger. The
batch has been aborted.
I am not trying to change the constraints on the rowguid column at all, only on another column that is acting as a FK. Other columns I want to set to be not null because the record doesn't make any sense without that information (i.e. on a customer, the customer name).
Questions:
Is there a way to update columns to be 'not null' without turning off replication then turning it back on again?
Is this even the best way to do this - should I be using a constraint instead?
Apparently SSMS makes changes to tables by dropping them and recreating them. So just needed to make the changes using T-SQL statement.
ALTER TABLE dbo.MyTable ALTER COLUMN MyColumn nvarchar(50) NOT NULL
You need to script out your change in T-SQL statements as SQL Server Management Studio will look to drop and re-create the table, as opposed to simply adding the additional column.
You will also need to add the new column to your Publications.
Please note that changing a column in this manner can be detrimental to the performance of Replication. Dependent on the size of the table you are altering, can lead to a lot of data being replicated. Consider that although your table modification can be performed in a single statement, if 1 million rows are affected then 1 million updates will be generated at the Subscriber, NOT a single update statement as is commonly thought.
The hands on, improved performance approach.......
To perform this exercise you need to:
Backup your Replication environment by scripting out your entire configuration.
Remove the table from Replication at
both Publishers/Subscribers
Add the column at each
Publisher/Subscriber.
Apply the Update locally at each
Publisher/Subscriber.
Add the table back into Replication.
Validate that transactions are being
Replicated.

Resources