How to Alter Column from nvarchar(max) to nvarchar(50) - sql-server

I have an existing table in SQL SERVER 2008 with one of its column as NVARCHAR(MAX) and it only has values of less than 10 characters in it.
This table is in production and has data in it.
I have got a requirement wherein I have to Alter this column from NVARCHAR(MAX) to NVARCHAR(50). The SQL Server gives some Truncation error while doing this operation, even though the data in that column is less than 10 characters.
This is my script:
ALTER TABLE [dbo].[Table] ALTER COLUMN [Column1] NVARCHAR ( 50 ) NOT NULL

First Check Your table data with this query:
SELECT DATALENGTH(Column_Name) AS FIELDSIZE, Column_Name
FROM Table_Name
If everything is fine, you may have checked the Prevent Saving Changes option. Follow these steps to check:
Tools > Designers Uncheck Prevent saving changes that require table re-creation

If you are sure that you wouldn't lose data, then:
Update myTable set myNVMaxCol = left(coalesce(myNVMaxCol,''),50);
Alter table myTable alter column myNVMaxCol nvarchar(50) not null;

Related

Change the max value of nvarchar in SQL database without deleting and rebuilding the table

Currently I have a SQL database with a column value of nvarchar(255) I need to change this to be nvarchar(600) when I edit it in the SQL visual studio on the server a warning pops up and states that the table must be deleted and rebuilt for my changes to be made. I DO NOT want to have to do this on the advice on the developer who built the program in the first place. (He is unable to make the change for me at this time).
I have seen a lot of answers that advise to Uncheck "Prevent saving changes that require ..." in the settings but again this is something I am reluctant to do on the advise of many others on this site and elsewhere.
Does anyone have any suggestions on how to change this max value without having to delete and rebuild the table?
Would a simple ALTER statement work? The field does not allow NULL values would something like this work?
ALTER TABLE dbo.myTable
ALTER COLUMN myColumn VARCHAR(600)
SET XACT_ABORT ON
BEGIN TRAN
ALTER TABLE dbo.myTable
DROP CONSTRAINT DF_myTable_myColumn
ALTER TABLE dbo.myTable
ALTER COLUMN myColumn VARCHAR(600) NOT NULL
ALTER TABLE dbo.myTable
ADD CONSTRAINT DF_myTable_myColumn DEFAULT('foo') FOR myColumn
COMMIT TRAN

Running an alter table alter column statement more than once in SQL Server

Are there any negative implications to running an alter table alter column statement more than once in SQL Server?
Say I alter a column's datatype and nullability like this:
--create table
create table Table1
(
Column1 varchar(50) not null
)
go
--insert some records
insert into Table1 values('a')
insert into Table1 values('b')
go
--alter once
alter table Table1
alter column Column1 nvarchar(250) not null
go
--alter twice
alter table Table1
alter column Column1 nvarchar(250) not null
go
The above set of sql all works and I have tested these. I could also test for the properties in the alter statements. The question is that is there any advantage to say checking if the column is not already nullable before altering.
After the first alter, does SQL Server figure out that the table has already been altered and hence the 2nd alter essentially does nothing?
Are there any differences across different versions of SQL Server about how this is handled?
Thanks,
Ilias
This is a metadata only operation.
It doesn't have to read or write any of the data pages belonging to Table1. It isn't quite a no-op though.
It will still start up a transaction, acquire a schema modification lock on the table and update the modified column in the row for this table in sys.sysschobjs (exposed to us through the modified_date column in sys.objects).
Moreover because the table has been modified any execution plans referencing the table will need to be recompiled on next usage.

Column not found

I tried below in sql server management, in a single query.
alter table add column amount2
update table set amount2=amount
I am getting column amount2 not found.
Can anyone tell me why this error?
That is not valid syntax (misses table name and column datatype) but in management studio use the batch separator GO between adding a column to an existing table and statements referencing the new column anyway.
Or alternatively you can use EXEC to execute it in a child batch.
SQL Server tries to compile all statements in the batch before execution and this will fail when it encounters the statement using this column.
There's a couple things wrong here.
The correct syntax for adding a column is MSDN - ALTER TABLE
ALTER TABLE [TableName] ADD [ColumnNAME] [DataType]
'Table' is a Reserved Keyword in SQL Server, although it is possible to have a table named 'Table'. You need to include brackets when referencing it.
SELECT * FROM [Table]
All together, you need
ALTER TABLE [Table] ADD [Amount2] INT
GO -- See Martin's answer for reason why 'GO' is needed here
UPDATE [Table] SET [Amount2] = [Amount]
You can get around this problem like this:
-- Alter the table and add new column "NewColumn"
ALTER TABLE [MyTable] ADD [NewColumn] CHAR(1) NULL;
-- Set the value of NewColumn
EXEC ('UPDATE [MyTable] SET [NewColumn] = ''A'' ');

SQL Server : alter table type

What happens when you execute the same alter column several times, e.g:
ALTER table1 ALTER column column1 varchar(40)
ALTER table1 ALTER column column1 varchar(40)
...
Does SQL Server compare altering types in first place or does it use the same mechanism for every alter?
You can check the transaction log, or use table change tracking, or use CDC to track, then you will find out what id the difference between first time and second time. You will see no difference.

How to change column datatype in SQL Server database without losing data?

I have SQL Server database and I just realized that I can change the type of one of the columns from int to bool.
How can I do that without losing the data that is already entered into that table?
You can easily do this using the following command. Any value of 0 will be turned into a 0 (BIT = false), anything else will be turned into 1 (BIT = true).
ALTER TABLE dbo.YourTable
ALTER COLUMN YourColumnName BIT
The other option would be to create a new column of type BIT, fill it from the old column, and once you're done, drop the old column and rename the new one to the old name. That way, if something during the conversion goes wrong, you can always go back since you still have all the data..
ALTER TABLE tablename
ALTER COLUMN columnname columndatatype(size)
Note: if there is a size of columns, just write the size also.
If it is a valid change.
you can change the property.
Tools --> Options --> Designers --> Table and Database designers --> Uncheck --> Prevent saving changes that required table re-creation.
Now you can easily change the column name without recreating the table or losing u r records.
if you use T-SQL(MSSQL); you should try this script:
ALTER TABLE [Employee] ALTER COLUMN [Salary] NUMERIC(22,5)
if you use MySQL; you should try this script:
ALTER TABLE [Employee] MODIFY COLUMN [Salary] NUMERIC(22,5)
if you use Oracle; you should try this script:
ALTER TABLE [Employee] MODIFY [Salary] NUMERIC(22,5)
Why do you think you will lose data? Simply go into Management Studio and change the data type. If the existing value can be converted to bool (bit), it will do that. In other words, if "1" maps to true and "0" maps to false in your original field, you'll be fine.
Go to Tool-Option-designers-Table and Database designers and Uncheck Prevent saving option
for me , in sql server 2016, I do it like this
*To rename column Column1 to column2
EXEC sp_rename 'dbo.T_Table1.Column1', 'Column2', 'COLUMN'
*To modify column Type from string to int:( Please be sure that data are in the correct format)
ALTER TABLE dbo.T_Table1 ALTER COLUMN Column2 int;
Alter column data type with check type of column :
IF EXISTS(
SELECT 1
FROM sys.columns
WHERE NAME = 'YourColumnName'
AND [object_id] = OBJECT_ID('dbo.YourTable')
AND TYPE_NAME(system_type_id) = 'int'
)
ALTER TABLE dbo.YourTable ALTER COLUMN YourColumnName BIT
In compact edition will take size automatically for datetime data type i.e. (8) so no need to set size of field and generate error for this operation...
I can modify the table field's datatype, with these following query: and also in the Oracle DB,
ALTER TABLE table_name
MODIFY column_name datatype;
Replace datatype without losing data
alter table tablename modify columnn newdatatype(size);

Resources