Executing a SQL ALTER TABLE STATEMENT with a variable value - sql-server

I have added a GUID field into my database tables and I want to update existing users by creating a guid value and then storing this for the related fields but I cant seem to execute the statement when I am using a variable, here is my code:
--Declaration of Script Variables
DECLARE #companyGUID UNIQUEIDENTIFIER
DECLARE #companyDomain NVARCHAR(256)
SET #companyGUID = NEWID()
SET #companyDomain = 'DOMAIN NAME HERE'
--Company Table Update
ALTER TABLE Company ADD GUID UNIQUEIDENTIFIER DEFAULT #companyGUID NOT null
ALTER TABLE Company ADD HasCampaignMonitor BIT
ALTER TABLE Company ADD CampaignMonitorListID NVARCHAR(32)
ALTER TABLE Company ADD CampaignMonitorApiKey NVARCHAR(32)
ALTER TABLE Company ADD CampaignMonitorClientID NVARCHAR(32)
ALTER TABLE Company ADD CampaignMonitorIntegratorID NVARCHAR(16)
ALTER TABLE Company ADD CampaignMonitorRedirectUrl NVARCHAR(256)
UPDATE Company SET GUID = #companyGUID where CompanyID = 1
UPDATE Company SET HasCampaignMonitor = 0 where CompanyID = 1
--User Table Update
ALTER TABLE User ADD GUID UNIQUEIDENTIFIER DEFAULT #companyGUID
ALTER TABLE User ADD DomainStub NVARCHAR(256) DEFAULT #companyDomain
--Activity Progress Table Update
ALTER TABLE ActivityProgress ADD GUID UNIQUEIDENTIFIER DEFAULT #companyGUID
--Answer Table Update
ALTER TABLE Answer ADD GUID UNIQUEIDENTIFIER DEFAULT #companyGUID

You can not use variables in alter statement. The default value is a constraint which can use any static values and some function as the default value.
ALTER TABLE modifies the table's structure and not the stored data.
Alter your tables (possibly with NULL values in the GUID column), Update the new columns, Alter the column with NOT NULL constraint.

Related

Alter sql server table Issue

I already created table in database. Now, I need to add "Identity" Column. Please suggest.
Create Cus(id int Pk,Name varchar2(50),Age int);
insert into Cus(id,Name,Age) values (1,'abc',12);
// here i need to add "Identity"
alter table Cus alter column id Identity(1,1)
You cannot use Alter command to add an identity to the table.
Here, you need to create dummy column and drop existing one.
Create table Cus(id int ,[Name] varchar(50),Age int);
insert into Cus(id,[Name],Age) values (1,'abc',12);
Alter Table Cus Add dummyid int identity(1,1)
Alter Table Cus Drop Column id
Exec sp_rename 'Cus.dummyid ', 'id', 'Column'
No you cannot make any column identity after creating from the query.
You have 2 options, either make it from SQL Management Studio or Create another column and copy with identity .
From Management Studio.
Step 1: Select Table design.
Step 2: Change Column properties.
Step 3: Save
Or
You need to create new column with identity.
Create column with identity `Alter table Tablename add newcol int identity(1,1)
Then copy your data from previous column to this column by setting Identity_Insert ON.
Then drop your previous column.
After that change column name by using sp_rename.
Note: But this will change the ordinal position of your column.
ANOTHER OPTION
Create new table with similar structure just make your column
identity whichever you want to be.
Copy data from your old table to new table.
Drop old table.
Change name of new table with old table.
Edit:
For case of Foreign Key relationship
If they are not so many and feasible, then you may drop the constraint.
ALTER TABLE Yourtable
DROP FOREIGN KEY FK_PersonOrder;
Then follow the above steps and recreate them at the last.
ALTER TABLE Yourtable
ADD FOREIGN KEY (yourid) REFERENCES Persons(PersonID);
Finally i got Solution,
I added new column in 'Cus' table.
alter table Cus add tempCusId int identity;
i removed FK relation in User's Table
and i updated identity values in User Table
update user set id=1 where id= 1;
I Compared Id and TempCusId. After update I removed "Pk" relation in Cus table droped Column "Id",i made "TempCusId" as a "Pk" and identity. Finally User table it self "Id" Column I made FK relation.
And if u have multiple values there than go for a "While" loop
DECLARE #NumberofRowint int=30;
DECLARE #inirow INT=23;
Declare #Grade int ;
WHILE #inirow<= #NumberofRow
BEGIN
DECLARE #ProductID INT=(select Id from [Cus] where id=#inirow)
Set #Grade=(select id from Cus where id=#ProductID)
IF(#Grade= #inirow)
BEGIN
updatetbl_Users set Id=#inirow where id=#ProductID
END
SET #inirow = #inirow + 1;
END;

Alter Column to Not Null where System Versioned column was nullable

I'm using SQL Server and system-versioned (temporal) tables. In my main table, I have an INT column that's currently allowing NULLs. I want to update this to not allow nulls, but the system/history copy of the table allows nulls.
I run this statement:
ALTER TABLE dbo.MyTable
ALTER COLUMN MyInt INT NOT NULL;
And I get this error:
Cannot insert the value NULL into column 'MyInt', table 'mydb.dbo.MyTable_History'; column does not allow nulls. UPDATE fails.
I had created the system versioned table using this script:
ALTER TABLE dbo.MyTable
ADD
ValidFrom DATETIME2 (2) GENERATED ALWAYS AS ROW START HIDDEN CONSTRAINT DFMyTable_ValidFrom DEFAULT DATEADD(SECOND, -1, SYSUTCDATETIME()),
ValidTo DATETIME2 (2) GENERATED ALWAYS AS ROW END HIDDEN CONSTRAINT DFMyTable_ValidTo DEFAULT '9999.12.31 23:59:59.99',
PERIOD FOR SYSTEM_TIME (ValidFrom, ValidTo);
ALTER TABLE dbo.MyTable
SET (SYSTEM_VERSIONING = ON (HISTORY_TABLE = dbo.MyTable_History));
GO
Is there some other way I can make my main table's column non-nullable in this scenario? I suppose I could (maybe) manually update the existing system-versioned null values with an arbitrary garbage value, but it seems like this scenario should be supported with temporal tables.
I also looked at this and it seems you have to update the NULL values in the system version column to some value.
ALTER TABLE dbo.MyTable
SET (SYSTEM_VERSIONING = OFF)
GO
UPDATE dbo.MyTable_History
SET MyInt = 0 WHERE MyInt IS NULL --Update to default value
UPDATE dbo.MyTable
SET MyInt = 0 WHERE MyInt IS NULL --Update to default value
ALTER TABLE dbo.MyTable
ALTER COLUMN MyInt INT NOT NULL
ALTER TABLE dbo.MyTable_History
ALTER COLUMN MyInt INT NOT NULL
GO
ALTER TABLE dbo.MyTable
SET (SYSTEM_VERSIONING = ON (HISTORY_TABLE = dbo.MyTable_History));
GO
I got this issue when I was trying to add a new non-null column. I was originally trying to create the column as nullable, update all the values, and then set it to non-nullable:
ALTER TABLE dbo.MyTable
ADD COLUMN MyInt INT NULL;
GO
UPDATE dbo.MyTable
SET MyInt = 0;
GO
ALTER TABLE dbo.MyTable
ALTER COLUMN MyInt INT NOT NULL;
But I managed to get around it by using a temporary default constraint instead:
ALTER TABLE dbo.MyTable
ADD COLUMN MyInt INT NOT NULL CONSTRAINT DF_MyTable_MyInt DEFAULT 0;
ALTER TABLE dbo.MyTable
DROP CONSTRAINT DF_MyTable_MyInt;
Whilst you can change the schema of temporal tables there are certain actions that you cannot do by a direct ALTER whilst a table is system versioned. One of those is to change a Nullable column to be NOT NULL.
See Important Remarks - Changing the schema of a system-versioned temporal table
In this scenario the only thing you can do is to turn off system versioning using the following:
ALTER TABLE schema.TableName SET (SYSTEM_VERSIONING = OFF);
This leaves you with 2 separate tables - the table itself and it's history table both as separate objects. You can now make your schema updates to BOTH tables (they have to be schema aligned) and then you can turn system versioning back on:
ALTER TABLE schema.TableName SET (SYSTEM_VERSIONING = ON);

ALTER table to increase column size does not reflect in History (versioned) table

I am currently using SQL Server 2016 and I have a table with SYSTEM VERSIONING TURNED ON. My alter command to increase the column size does not reflect in the history table (versioned table). Please can you advise?
I created the table using the below command
CREATE TABLE Report (
ReportId INTEGER NOT NULL,
ReportName VARCHAR(300) NULL,
CONSTRAINT PK_RPT PRIMARY KEY (ReportId)
)
ALTER TABLE Report
ADD ValidFrom DATETIME2 GENERATED ALWAYS AS ROW START NOT NULL DEFAULT SYSUTCDATETIME(),
ValidTo DATETIME2 GENERATED ALWAYS AS ROW END NOT NULL DEFAULT CAST('9999-12-31 23:59:59.9999999' AS DATETIME2),
PERIOD FOR SYSTEM_TIME (ValidFrom, ValidTo);
ALTER TABLE ICEBERG.Report
SET (SYSTEM_VERSIONING = ON (HISTORY_TABLE = ICEBERG.ReportHistory));
I am now trying to modify the column size ReportName in this table but the change in column size does not reflect in the ReportHistory table.
ALTER TABLE ICEBERG.Report SET (SYSTEM_VERSIONING = OFF); -- note comment below
ALTER TABLE ICEBERG.Report ALTER COLUMN ReportName VARCHAR(500) NULL;
ALTER TABLE ICEBERG.Report SET (SYSTEM_VERSIONING = ON); -- note comment below
Please note , I have tried to execute only the alter table command without turning SYSTEM_VERSIONING ON/OFF as above, even that does not help.

Alter column Datatype

I have a table dbo.ExceptionMessage and now I want to change the column datatype nvarchar(100) to nvarchar(MAX). I used alter query for changing this
ALTER TABLE dbo.ExceptionMessage ALTER COLUMN Address nvarchar(MAX)
and while excecuting this query it shows some error like.
The object 'DF_ExceptionMessage_Address' is dependent on column 'Address'.
ALTER TABLE ALTER COLUMN Address failed because one or more objects access this column.
How can we solve this...
First Delete all Constraint Like this
ALTER TABLE TableName DROP CONSTRAINT [DF__TableName__ColumnName__FieldName]
and then perform change
ALTER TABLE dbo.ExceptionMessage ALTER COLUMN Address nvarchar(MAX)
then re enter the constraints
You have to find out which type of constraint DF_ExceptionMessage_Address is, drop it, alter the column type and then re-create the constraint if you need it.
you try first:
ALTER TABLE <tablename> DROP CONSTRAINT <Con_Name>;
And Then Do your Alter
ALTER TABLE dbo.ExceptionMessage ALTER COLUMN Address nvarchar(MAX)
Again Add Constraint
thiz help you to alter
alter table TableName
alter column ColumnName nvarchar(200);

ALTER TABLE constraint problem

I'm trying to run the following SQL statement:
IF OBJECT_ID('MyTable') IS NOT NULL
DROP TABLE MyTable
SELECT
a.UserId
INTO
MyTable
FROM
UsersTable a
WHERE
a.UserId='12359670-1DC9-4A0A-8AE5-29B664C1A57E'
ALTER TABLE MyTable ALTER COLUMN UserId UNIQUEIDENTIFIER NOT NULL
ALTER TABLE MyTable ADD PRIMARY KEY(UserId)
However, I get the following error:
Cannot define PRIMARY KEY constraint on nullable column in table 'MyTable'.
Any ideas?
This assumes SQL Server based on UNIQUEIDENTIFIER
Put a GO between (or relevant batch separator if not SQL Server)
....
ALTER TABLE MyTable ALTER COLUMN UserId UNIQUEIDENTIFIER NOT NULL
GO
ALTER TABLE MyTable ADD PRIMARY KEY(UserId)
At batch compile time, the column is nullable. So break up the batches.
SQL isn't a line by line procedural language
You'll have to do this in a stored procedure
ALTER TABLE MyTable ALTER COLUMN UserId UNIQUEIDENTIFIER NOT NULL
EXEC('ALTER TABLE MyTable ADD PRIMARY KEY(UserId)')
Found a solution.
I'm using the following statement:
EXEC sp_ExecuteSQL N'ALTER TABLE MyTable ALTER COLUMN UserId UNIQUEIDENTIFIER NOT NULL'
EXEC sp_ExecuteSQL N'ALTER TABLE MyTable ADD PRIMARY KEY(UserId)'
You don't need dynamic SQL. Just create the table and the key first.
CREATE TABLE MyTable (UserId UNIQUEIDENTIFIER NOT NULL PRIMARY KEY);
INSERT INTO MyTable (UserId)
SELECT UserId
FROM UsersTable
WHERE UserId='12359670-1DC9-4A0A-8AE5-29B664C1A57E';

Resources