Altering SQL table to add column - sql

I currently have a table with four columns - i wanted to add a fifth column but having some trouble.
I open the table in sql server studio management 2008 and i added the column info like so:
CREATE TABLE [dbo].[Case]
(
CaseId UNIQUEIDENTIFIER DEFAULT (newid()) NOT NULL,
CaseNumber NVARCHAR(50) NOT NULL,
CourtId INT NOT NULL,
DateOpened DATETIME NOT NULL,
)
my addition:
CREATE TABLE [dbo].[Case]
(
CaseId UNIQUEIDENTIFIER DEFAULT (newid()) NOT NULL,
CaseNumber NVARCHAR(50) NOT NULL,
CaseName NVARCHAR(50),
CourtId INT NOT NULL,
DateOpened DATETIME NOT NULL,
)
After adding CaseName column, i tried executing the table in Management Studio but i got the error message "There is already an object named 'Case' in the database."
I tried saving and then building my database hoping that the column will be added but that wasn't successful. I tried a New Query and writing the 'Alter table "case" add CaseName nvarchar(50) but again without luck. It shows that the file is changed with the new column because i saved it but after building my overall database it isn't making any changes. Any helpful tips will be great.

You want to ALTER, as follows:
ALTER TABLE [dbo].[Case] ADD CaseName NVARCHAR(50)
Better yet, you can check for the existance of the column first:
if not exists (SELECT 1 FROM sysobjects INNER JOIN syscolumns ON
sysobjects.id = syscolumns.id
WHERE sysobjects.name = N'Case' AND syscolumns.name = N'CaseName')
ALTER TABLE [dbo].[Case] ADD CaseName NVARCHAR(50)

you should try this
ALTER TABLE [dbo].[Case]
ADD CaseName NVARCHAR(50)
You are trying to create another table Case but one already exists that's why you have an error. When you want to edit a table, you have to use Alter table

Use an Alter table statement instead of Create
If you can't get the Alter statement to work for some reason, you could also drop the existing table and create a new one with the new field, but all your existing rows will be lost.
If you're using SSMS, you can Design the table instead of Edit to add the column.

ALTER is what you need to investigate (F1)
An alternative is.
Create a new table
CREATE TABLE [dbo].[Case2]
(
CaseId UNIQUEIDENTIFIER DEFAULT (newid()) NOT NULL,
CaseNumber NVARCHAR(50) NOT NULL,
CourtId INT NOT NULL,
DateOpened DATETIME NOT NULL,
newcolumn INT NULL
)
Move data from existing table into the new one
INSERT INTO [dbo].[Case2]
SELECT * FROM [dbo].[Case]
Then
DROP TABLE [dbo].[Case]
Then in management studio right-click 'Case2' and re-name it 'Case'

I recommend checking for the existence of the column prior to adding it, especially important when you work with migration scripts.
Here is how I usually do it:
IF NOT EXISTS(SELECT * FROM sys.columns WHERE Name = N'ColumnName' AND Object_ID = Object_ID(N'TableName'))
BEGIN
ALTER TABLE [dbo].TableName ADD ColumnName NVARCHAR(512) null
END

Related

Postgres copy table schema is_null constraints not included

i have a table with the ff columns and constraints :
create table newtable(
id int4 not null primary key,
lastname varchar(50) not null,
firstname varchar(50) not null,
middlename varchar(50) not null
)
I'm developing a workflow script (KNIME) that would test the schema from the source to target.
so i use the ff. code :
CREATE TABLE xtable
AS TABLE newtable;
When i checked the is_null constraints, it was set to 'yes' (but in the original table, it was set to 'no'). How can i include the constraints using the above-mentioned code script?
It appears that you can't achieve it with the current approach. The best option I know is the following query:
CREATE TABLE xtable (LIKE newtable INCLUDING ALL);
INSERT INTO xtable SELECT * FROM newtable;
You can read about this syntax here.

So I can't have NOT NULL in column definition of temporal tables?

I am using SQL Server 2016 and trying to create Temporal table. Here is the definition:
USE zbachoreTest
GO`enter code here`
IF EXISTS (SELECT 1 FROM sys.tables WHERE name = 'People' AND temporal_type_desc ='SYSTEM_VERSIONED_TEMPORAL_TABLE' )
ALTER TABLE dbo.People SET( SYSTEM_VERSIONING = OFF)
DROP TABLE IF EXISTS dbo.People
CREATE TABLE dbo.People(
PersonID INT IDENTITY(1,1) NOT NULL CONSTRAINT PK_People PRIMARY KEY(PersonID),
FirstName VARCHAR(50) NOT NULL,
LastName VARCHAR(50) NULL,
StartTime DATETIME2 GENERATED ALWAYS AS ROW START NOT NULL
CONSTRAINT DF_People_StartTime DEFAULT SYSDATETIME(),
EndTime DATETIME2 GENERATED ALWAYS AS ROW END NOT NULL
CONSTRAINT DF_People_EndTime DEFAULT CONVERT(DATETIME2,'9999-12-31 23:59:59.9999999'),
PERIOD FOR SYSTEM_TIME(StartTime,EndTime)
) WITH (SYSTEM_VERSIONING = ON (HISTORY_TABLE = dbo.PeopleHistory))
when I run the above code, I am getting the following error message:
Msg 13531, Level 16, State 1, Line 7
Setting SYSTEM_VERSIONING to ON failed because column 'FirstName' does not have the same nullability attribute in tables 'zbachoreTest.dbo.People' and 'zbachoreTest.dbo.PeopleHistory'.
Any smart folks out there please help. Thanks!
Yes, you can.
Do drop table dbo.PeopleHistory first. If it already exists, it will be only validated, not recreated.
From: https://learn.microsoft.com/en-us/sql/relational-databases/tables/creating-a-system-versioned-temporal-table
The history table must always be schema-aligned with the current or
temporal table, in terms of number of columns, column names, ordering
and data types.
and
If the table specified by the HISTORY_TABLE parameter already exists,
it will be validated against the newly created temporal table in terms
of schema consistency and temporal data consistency. If you specify an
invalid history table, the CREATE TABLE statement will fail.

SQL Server Create Table With Column Unique Not Null and Not Empty(Check)

How to create a table with a column which is unique, not null and not empty(Check)?
I tried below Query
CREATE TABLE Persons
(
P_Id int NOT NULL UNIQUE,
LastName nvarchar(255) NOT NULL,
FirstName nvarchar(255),
Address nvarchar(255),
City nvarchar(255),
CHECK (P_Id>0)
)
When i try to create a table with both UNIQUE and CHECK constraint its throwing following error. Is it possible to use two constraint in a single query?
Major Error 0x80040E14, Minor Error 25501
> CREATE TABLE Persons
(
P_Id int NOT NULL UNIQUE,
LastName nvarchar(255) NOT NULL,
FirstName nvarchar(255),
Address nvarchar(255),
City nvarchar(255),
CHECK (P_Id>0)
)
There was an error parsing the query. [ Token line number = 8,Token line offset = 1,Token in error = CHECK ]. I am using SQL Server 2008.
CREATE TABLE tab
(
id INT,
notnullandnotemptystr VARCHAR(10) NOT NULL UNIQUE CHECK (DATALENGTH(notnullandnotemptystr) > 0)
)
It should be some thing like this.
CREATE TABLE [dbo].[TABLE1](
[COL1] [nvarchar](50) NOT NULL UNIQUE
)
ALTER TABLE [dbo].[TABLE1] WITH CHECK
ADD CONSTRAINT [CK_TABLE1] CHECK (([COL1]<>N''))
for this problem you can use Constraint in sql server
ALTER TABLE TBL WITH CHECK ADD CONSTRAINT [CK_TBL] CHECK
(([dbo].[TBLCheckCustomeUnique](ID)=(1)))
TBLCheckCustomeUnique is a user define function that check this conditions
You can controll the uniqueness of a column or column set by the UNIQUE constraint.
The data stored in the column or column set could be checked/controlled (and forced with various rules) by the CHECK constraint.
The CHECK constraint to achieve your goal is the following:
ALTER TABLE [YourTable]
ADD CONSTRAINT CK_CheckConstraintName
CHECK (LEN([YourColumn]) >= {MinimumColumnWidth})
You can add the constraints in the CREATE TABLE statement or if the table already exists you can add it with the ALTER TABLE .. ADD CONSTRAINT statement.

Drop temp table if it exists

Friends,
I am creating a temp table. The script may be run several times so I need to check if the temp table exist then drop it. I have the written the code below but I get an error when running the script twice, that the table already exists:
There is already an object named '#lu_sensor_name_19' in the database.
It appears that IF OBJECT_ID('alarm..#lu_sensor_name_19') IS NOT NULL does not return true when the tablle is not null. What am I doing wrong?
IF OBJECT_ID('alarm..#lu_sensor_name_19') IS NOT NULL
BEGIN
DROP TABLE #lu_sensor_name_19
END
CREATE TABLE #lu_sensor_name_19(
sensorname_id int NOT NULL,
sensorname nvarchar(50) NOT NULL,
paneltype_id smallint NOT NULL,
panel_version_id int NULL,
prefix_allowed tinyint NOT NULL,
base_allowed tinyint NOT NULL,
suffix_allowed tinyint NOT NULL,
key_value int NULL,
sort_index int NULL,
device_allowed tinyint NOT NULL,
sensor_name_group_id smallint NOT NULL,
)
Temp #Tables are created in tempdb. Try this:
IF OBJECT_ID('tempdb..#lu_sensor_name_19') IS NOT NULL
BEGIN
DROP TABLE #lu_sensor_name_19
END
CREATE TABLE #lu_sensor_name_19...
SQL Server 2016 added the ability to do the drop in one line:
DROP TABLE IF EXISTS #lu_sensor_name_19
CREATE TABLE #lu_sensor_name_19...
Use this.
IF OBJECT_ID('tempdb.dbo.##myTempTable', 'U') IS NOT NULL
BEGIN
DROP TABLE ##myTempTable;
--DROP TABLE ##tempdb.dbo.myTempTable;
/* Above line commented out, because it generates warning:
"Database name 'tempdb' ignored, referencing object in tempdb.",
which is a pain in the neck if you are using a temp table to generate SQL code,
and want to print the code to the screen.*/
END;
GO
CREATE TABLE ##myTempTable(
FooBar nvarchar(128) not null,
);
And, in SQL Server 2016, you can write:
DROP TABLE IF EXISTS ##myTempTable

SQL Server trigger update column from another table

I am trying to create a fairly simple SQL Server trigger, hope someone can help.
I have a table with structure like this:
Table #1:
CREATE TABLE `teg_priority` (
`UCIDN` BIGINT(50) NULL DEFAULT NULL,
`CIDN` BIGINT(50) NOT NULL,
`CustomerName` VARCHAR(200) NOT NULL,
`NGM` VARCHAR(150) NULL DEFAULT NULL,
`Service_Manager` VARCHAR(150) NULL DEFAULT NULL,
`CBS` LONGTEXT NULL,
`Tag` VARCHAR(50) NOT NULL,
PRIMARY KEY (`CIDN`)
)
and another table (table #2):
CREATE TABLE `custalign` (
`UCIDN` BIGINT(20) NOT NULL,
`CIDN` BIGINT(20) NOT NULL,
`CustomerName` VARCHAR(255) NOT NULL,
PRIMARY KEY (`CIDN`)
)
I am trying to set up a trigger where every time a new record is inserted into the first table that the following query will be run as a trigger to update field UCIDN in table 1
update teg_priority
set teg_priority.UCIDN = (select UCIDN from custalign
where teg_priority.CIDN = custalign.CIDN)
The above query works i just don't know how to write it as a trigger statement.
Please help.
CREATE TRIGGER dbo.Teg_priority_after_insert
ON dbo.teg_priority AFTER INSERT
AS
UPDATE inserted
set inserted.UCIDN = (select UCIDN from custalign
where inserted.CIDN = custalign.CIDN)
That's your answer. You might consider a change in approach; assuming it doesn't require a total re-work of your process-flow. I can't really suggest more without knowing what you're ultimately trying to accomplish.
In SQL Server triggers, there is an inserted and a deleted table automatically-generated to which you may refer. Each respectively contains the new and old records as a result of whatever statement AFTER [INSERT],[UPDATE],[DELETE]. The inserted table is accessible to AFTER INSERT and UPDATE triggers, while the deleted table is accessible to AFTER UPDATE and DELETE triggers.
That might be more than you wanted to know, but I thought you'd benefit from a brief explanation of where the inserted table came from in my code.
[Insert all the usual caveats about trying not to use triggers wherever possible here.]
try out this..hope this will helps you
For MySQL
CREATE TRIGGER teg_priorityTrigger AFTER INSERT ON teg_priority
FOR EACH ROW
BEGIN
UPDATE inserted
set inserted.UCIDN = (select UCIDN from custalign
where inserted.CIDN = custalign.CIDN)
END
For SQL Server
CREATE TRIGGER teg_priorityTrigger ON dbo.teg_priority AFTER INSERT
AS
UPDATE inserted
set inserted.UCIDN = (select UCIDN from custalign
where inserted.CIDN = custalign.CIDN)
hope this will helps you...