Add column to existing table in SQL with IF/ ELSE Statement - sql

I am suing PgAdmin4
I have a table called Development. This table contains a column called Customer. I want to create a new column called Target which is equal to 1 when the Customer is null and 0 otherwise.
Here is my code:
ALTER TABLE development ADD COLUMN Target INTEGER;
IF Customer IS NULL then
SET Target = 1;
else
SET Target = 0;
END if;
I am getting this error:
ERROR: syntax error at or near "IF"
LINE 3: IF Customer IS NULL then
^
SQL state: 42601
Character: 53

Most databases support generated columns. The syntax is something like this:
alter table development add column int generated always as
(case when customer is null then 1 else 0 end);
The exact syntax varies by database.
This is much more powerful than adding a new column to the table, because a generated column always has the correct value -- even without an update.

You could use an update statement with a case expression:
UPDATE mytable
SET target = CASE WHEN customer IS NULL THEN 1 ELSE 0 END

Related

Use case condition in stored procedure to update table

I have an existing table in the database. I want to update a column value with 1 or 2 by making a condition on another column value of the same table and I want to do it with a script
Below is the stored procedure script which I wrote but it is not updating the table.
CREATE PROCEDURE [dbo].[updateDocumentCategory]
AS
BEGIN
UPDATE cmdocuments
SET docCategoryId = CASE
WHEN (docUploadable = 'Y') THEN 2
WHEN (docUploadable = 'N') THEN 1
END
END
Provided below is the sample data
This is a bit long for a column.
Indeed, it is not updating the table. How can I tell? If it did, then the value would be NULL, not 0.
This suggests that the problem is that the stored procedure is not being called. If that is the case, you can just update the table using the specified update statement.
However, if this is something that you really need to be consistent, I would suggest using a computed column:
ALTER TABLE cmdocuments ADD docCategoryId AS (
CASE WHEN docUploadable = 'Y' THEN 2
WHEN docUploadable = 'N' THEN 1
END);
This will ensure that docCategoryId has the correct value without having to update the table. Then the stored procedure won't even be needed.

Cannot add NOT NULL constraint [duplicate]

So I want to change a column in my SQL Server database to not allow nulls, but I keep getting an error. this is the sql statement I am using:
alter table [dbo].[mydatabase] alter column WeekInt int not null
and this is the error I am getting :
Msg 515, Level 16, State 2, Line 1
Cannot insert the value NULL into column 'WeekInt', table 'CustomerRadar.dbo.tblRWCampaignMessages'; column does not allow nulls. UPDATE fails.
The statement has been terminated.
I'm pretty sure my sql is right, and there are no nulls currently in the column I am trying to change so I am really not sure as to what is causing the problem. Any ideas? I'm stumped.
Clearly, the table has NULL values in it. Which you can check with:
select *
from mydatabase
where WeekInt is NULL;
Then, you can do one of two things. Either change the values:
update mydatabase
set WeekInt = -1
where WeekInt is null;
Or delete the offending rows:
delete from mydatabase
where WeekInt is null;
Then, when all the values are okay, you can do the alter table statement.
If you are trying to change a column to not null, and you are getting this error message, yet it appears the column has no nulls, ensure you are checking for is null and not = null (which gives different results).
Select * from ... where column is null
instead of
Select * from ... where column = null
I am adding this because it tripped me up and took a while to resolve.
This will work. You should send a default value, then it will change all the previous record to -1 in this example.
alter table [dbo].[mydatabase] alter column WeekInt int not null DEFAULT '-1';

Check if column exists then alter column from the table?

I want to write sql script that should check if column exists in the table, and then remove the column if previous statement is true. The database I use is Sybase ASE, and this is the code that I tried to use:
IF EXISTS (SELECT 1 FROM syscolumns WHERE id = object_id('users') AND name = 'maiden_name')
BEGIN
ALTER TABLE security DROP maiden_name
END
The code above executed successfully first time I run it. The second time I goth the error:
Invalid column name 'maiden_name'
If column does not exist the ALTER TABLE block of code shouldn't run. Is there a way to achieve this is Sybase? Thank you.
You can use dynamic SQL:
IF EXISTS (SELECT 1 FROM syscolumns WHERE id = object_id('users') AND name = 'maiden_name')
BEGIN
EXEC('ALTER TABLE security DROP maiden_name')
END;
The problem is that the parser is trying to parse the ALTER during the compilation phase, and it gets an error if the column does not exist.

How to make a query replace column if exist using sql-server query

I have a query as the below one:
alter table [toolDB].[dbo].[esn_sho] add esn_umts_sho_relation_key as Convert(nvarchar(50),[utrancell])+'_'+Convert(nvarchar(50),[utranrelation])
So All I need I want to replace esn_umts_sho_relation_key column if exist...
As I got this error:
[Microsoft][SQL Server Native Client 11.0][SQL Server]Column names in each table must be unique. Column name 'esn_umts_sho_relation_key' in table 'toolDB.dbo.esn_sho' is specified more than once
I tired to use the below code but it's doen't work:
IF NOT EXISTS (alter table [toolDB].[dbo].[esn_sho] add esn_umts_sho_relation_key as Convert(nvarchar(50),[utrancell])+'_'+Convert(nvarchar(50),[utranrelation]))
It gives me this error:
Incorrect syntax near the keyword 'alter'.
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near ')'
So I want to add If Exist in this query any one knows how to solve this prolem...
The column I already exist in the table ,but I want to replace it if exist to escape from this error...
IF COL_LENGTH('TableName', 'ColumnName') IS NOT NULL
BEGIN
-- Column Exists
-- here you can put your cond...
END
IF COL_LENGTH('[toolDB].[dbo].[esn_sho]', 'esn_umts_sho_relation_key') IS NOT NULL
BEGIN
-- Column Exists
alter table [toolDB].[dbo].[esn_sho] add esn_umts_sho_relation_key as Convert(nvarchar(50),[utrancell])+'_'+Convert(nvarchar(50),[utranrelation])---Put your condition in proper way...
END
IF EXISTS(SELECT * FROM DatabaseName where ColumnName = #YourParameter)
BEGIN
You Can Write Alter Query Here
END
ELSE
BEGIN
You Can Set Here AN Else Condition/Optional
END
To solve this particular issue, you can use the system tables. Try this
SELECT *
FROM sys.all_objects obj
JOIN sys.all_columns col ON obj.object_id = col.object_id
WHERE
obj.Name = #YourTableName
AND col.Name = #YourColumnName
This will give you the columns in your table if it exists. You can use this to make your decision about what you would do if it exists/doesn't exist.

Invalid column name on sql server update after column create

Does anyone see what's wrong with this code for SQL Server?
IF NOT EXISTS(SELECT *
FROM sys.columns
WHERE Name = 'OPT_LOCK'
AND object_ID = Object_id('REP_DSGN_SEC_GRP_LNK'))
BEGIN
ALTER TABLE REP_DSGN_SEC_GRP_LNK
ADD OPT_LOCK NUMERIC(10, 0)
UPDATE REP_DSGN_SEC_GRP_LNK
SET OPT_LOCK = 0
ALTER TABLE REP_DSGN_SEC_GRP_LNK
ALTER COLUMN OPT_LOCK NUMERIC(10, 0) NOT NULL
END;
When I run this, I get:
Msg 207, Level 16, State 1, Line 3
Invalid column name 'OPT_LOCK'.
on the update command.
Thanks.
In this case you can avoid the problem by adding the column as NOT NULL and setting the values for existing rows in one statement as per my answer here.
More generally the problem is a parse/compile issue. SQL Server tries to compile all statements in the batch before executing any of the statements.
When a statement references a table that doesn't exist at all the statement is subject to deferred compilation. When the table already exists it throws an error if you reference a non existing column. The best way round this is to do the DDL in a different batch from the DML.
If a statement both references a non existing column in an existing table and a non existent table the error may or may not be thrown before compilation is deferred.
You can either submit it in separate batches (e.g. by using the batch separator GO in the client tools) or perform it in a child scope that is compiled separately by using EXEC or EXEC sp_executesql.
The first approach would require you to refactor your code as an IF ... cannot span batches.
IF NOT EXISTS(SELECT *
FROM sys.columns
WHERE Name = 'OPT_LOCK'
AND object_ID = Object_id('REP_DSGN_SEC_GRP_LNK'))
BEGIN
ALTER TABLE REP_DSGN_SEC_GRP_LNK
ADD OPT_LOCK NUMERIC(10, 0)
EXEC('UPDATE REP_DSGN_SEC_GRP_LNK SET OPT_LOCK = 0');
ALTER TABLE REP_DSGN_SEC_GRP_LNK
ALTER COLUMN OPT_LOCK NUMERIC(10, 0) NOT NULL
END;
The root cause of the error is the newly added column name is not reflected in the sys.syscolumns and sys.columns table until you restart SQL Server Management Studio.
For your information,you can replace the IF NOT EXISTS with the COL_LENGTH function. It takes two parameters,
Table Name and
Column you are searching for
If the Column is found then it returns the range of the datatype of the column Ex: Int (4 bytes), when not found then it returns a NULL.
So, you could use this as follows and also combine 3 Statements into one.
IF (SELECT COL_LENGTH('REP_DSGN_SEC_GRP_LNK','OPT_LOCK')) IS NULL
BEGIN
ALTER TABLE REP_DSGN_SEC_GRP_LNK
ADD OPT_LOCK NUMERIC(10, 0) NOT NULL DEFAULT 0
END;
Makes it simpler.