How to alter column nvarchar length without drop
SqlSql ServerSsmsSql Problem Overview
I'm trying to alter the length of the column "Body" in table "Post" like this:
ALTER TABLE Post ALTER COLUMN Body nvarchar(8000) NOT NULL;
The column is defined as nvarchar(4000) and it gives me this error:
> Msg 2717, Level 16, State 2, Line 1 The size (8000) given to the parameter 'Body' exceeds the maximum allowed (4000).
Sql Solutions
Solution 1 - Sql
Use Max instead. If the column were declared as VARCHAR, 8000 would be ok.
ALTER TABLE Post ALTER COLUMN Body nvarchar(max) NOT NULL;
Solution 2 - Sql
In case, if the column has any constraint key like default, check .. ext, First we have dropped the key constraint from the column than alter the size of the column and alter your constraint to the column. The below steps will help you.
Steps are,
> ALTER TABLE MESSAGE_INBOX_VIEWERS DROP CONSTRAINT DF_CONST_TEXT
> ALTER TABLE MESSAGE_INBOX_VIEWERS ALTER COLUMN TEXT NVARCHAR(MAX)
> ALTER TABLE MESSAGE_INBOX_VIEWERS ADD CONSTRAINT DF_CONST_TEXT DEFAULT('') FOR TEXT
Solution 3 - Sql
For constraints you can use following
DECLARE @DEFCONSTRAINT VARCHAR(1000);
DECLARE @DropDFConstraitCmd VARCHAR(1000);
DECLARE @AlterDFColumnCmd VARCHAR(1000);
DECLARE @CreateDFConstraitCmd VARCHAR(1000);
DECLARE @CONSTRAINT_SAYI NUMERIC;
SET @DEFCONSTRAINT=(SELECT name
FROM sys.sysobjects
WHERE type = 'D' AND OBJECT_NAME(parent_obj) = 'TABLENAME' and name like 'DF__TABLENAME__COLUMNNAME%');
SET @CONSTRAINT_SAYI=(SELECT count(*)
FROM sys.sysobjects
WHERE type = 'D' AND OBJECT_NAME(parent_obj) = 'TABLENAME' and name like 'DF__TABLENAME__COLUMNNAME%');
SET @DropDFConstraitCmd = ' ALTER TABLE TABLENAME DROP CONSTRAINT ' +@DEFCONSTRAINT;
SET @AlterDFColumnCmd = ' ALTER TABLE TABLENAME ALTER COLUMN COLUMNNAME nvarchar(max) NOT NULL';
SET @CreateDFConstraitCmd = ' ALTER TABLE TABLENAME ADD CONSTRAINT ' +@DEFCONSTRAINT + ' DEFAULT ('' '') FOR COLUMNNAME ';
if @CONSTRAINT_SAYI > 0
exec (@DropDFConstraitCmd);
exec (@AlterDFColumnCmd);
exec (@CreateDFConstraitCmd);
Solution 4 - Sql
try NTEXT instead.
ALTER TABLE Post ALTER COLUMN Body NTEXT NOT NULL;
NTEXT is similar to NVARCHAR, but is designed more for BODY fields or comment fields that require large amount of text.