Add Column to Databricks Table Syntax Error - sql

I am trying to add a column based on a case when statement mapping status to status names. This is in Databricks, and i'm wondering if i'm having an issue with permissions or if my syntax is off somewhere. A similar statement worked in SQL server.
ALTER TABLE dbo.table
ADD status_name as (CASE WHEN status = '0' THEN 'Pink'
WHEN status = '9' THEN 'Green'
WHEN status = '8' THEN 'Blue'
WHEN status = '2' THEN 'Red'
ELSE 'Other'
END);
This is the error message I am getting:
Error in SQL statement: ParseException:
no viable alternative at input 'ALTER TABLE db.table\nADD status_name'(line 2, pos 4)
Anyone know where i'm going wrong here? Shouldn't the syntax be identical between data-bricks and sql server? The table names are different in Databricks.

I noticed that you missed COLUMN in your statement.
ALTER TABLE dbo.table
ADD **COLUMN** status_name

Related

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

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

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';

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.

Postgresql UPDATE syntax error on RAISE exception in CASE / IF condition

I am confused with writing Postgresql UPDATE query with CASE (or IF) condition.
Expected behavior: I have to raise an exception and do not do update if one specific field is not null.
Current behavior: I tries CASE and IF conditions, but every time I got syntax error: SQL Error [42601]: ERROR: syntax error at or near "exception".
Thoughts: maybe there is a way to achieve same result with adding constraint to table?
UPDATE public.SomeTable
SET Title = (
case when EndDate IS null
THEN 'new title'
ELSE raise exception 'Cannot update entity if EndDate is not null'
end),
Description = (
case when EndDate IS null
THEN 'new description'
ELSE raise exception 'Cannot update entity if EndDate is not null'
end)
WHERE Id=4
Version:
PostgreSQL 11.5 (Debian 11.5-1.pgdg90+1) on x86_64-pc-linux-gnu, compiled by gcc (Debian 6.3.0-18+deb9u1) 6.3.0 20170516, 64-bit
The only relatively convenient way I can think to do this uses updatable views:
create view vw_sometable as
select t.*
from sometable t
where endDate is null
with check option;
You would then insert into the view, rather than into the underlying table.
You can further refine this by giving update permissions on the view but not on the underlying table, so all updates need to go through the view.
Well, another method would not return an error, but it would not update the rows. Just include the condition in the where clause:
UPDATE public.SomeTable
SET Title = 'new title',
Description = 'new description'
WHERE Id = 4 AND EndDate is null';
You could add subsequent logic to check if any rows are updated and raise the error there.
remove case after end
UPDATE public.SomeTable
SET Title = (
case when EndDate IS null
THEN 'new title'
ELSE 'Cannot update entity if EndDate is not null'
end ),
Description = (
case when EndDate IS null
THEN 'new description'
ELSE 'Cannot update entity if EndDate is not null'
end )
WHERE Id=4

What is wrong with my UPDATE statement?

I just want to update the status of a booking using bookingid.
UPDATE flightbooking
SET status 'C' AS cancelledbooking
FROM flightbooking
WHERE bookingid = 10001;
I get the following error:
ERROR: syntax error at or near "'C'"
LINE 2: SET status 'C' AS cancelledbooking
Any help?
I would suggest:
UPDATE flightbooking
SET status = 'C'
WHERE bookingid = 10001;
This should work in any database, assuming you have the right table and columns.
FROM is not part of the FROM clause necessarily. In addition, how it gets interpreted varies among databases. Once you fix the SET clause, Postgres would update all rows (I think); SQL Server would update the matching row; Oracle and MySQL would generate an error.
You cannot use an alias within an update statement.
UPDATE flightbooking
SET status = 'C'
FROM flightbooking
WHERE bookingid = 10001;
AS is used for aliasing in SELECT context, not UPDATE.
This will work:
UPDATE flightbooking
SET status = 'C'
FROM flightbooking
WHERE bookingid = 10001;
Simply:
UPDATE flightbooking SET status = 'C' WHERE bookingid = 10001