Why is UPDATE statement not working in SQL code? - sql

I am trying to update one row of the storeID column. When I do the first code below, it runs but will not affect any row. However, the bottom two are producing the following error " The UPDATE statement conflicted with the REFERENCE constraint "Products_FK". The conflict occurred in database "group7", table "dbo.Products", column 'storeID'."
Could anyone help? Thanks!
Table in SQL
UPDATE Store
SET storeID='E50'
WHERE storeID='D50'
AND storeID is Null;
UPDATE Store
SET storeID='E50'
WHERE storeID='D50'
UPDATE Store
SET storeID='E50'
WHERE storeName='A Plus Cables'
Above is the code that I have tried and nothing is being updated.

The first one can't possibly match any rows, because a single value can't equal two different things at the same time:
WHERE storeID='D50'
AND storeID is Null
So that one is kind of a moot point. You'd need to update the WHERE clause to target the record(s) you want to target.
For the latter two, the error is telling you what's wrong. You're trying to write this value to a column:
SET storeID='E50'
But the error is telling you:
That column is a foreign key to another table. (Products?)
The value you're writing isn't presentin that other table.
So your options are:
Use a value that is present in the other table.
Use NULL (and update the column to allow NULL if necessary).
Remove the foreign key constraint to that other table.

Related

Add column to table with existing data in SQL Server

I have a table Rates with data in it and I need to add new column to the table however I get the error:
ALTER TABLE only allows columns to be added that can contain nulls, or have a DEFAULT definition specified, or the column being added is an identity or timestamp column, or alternatively if none of the previous conditions are satisfied the table must be empty to allow addition of this column. Column 'CreatedOn' cannot be added to non-empty table 'RateIncreases' because it does not satisfy these conditions
How can I do this, I have disabled prevent saving changes that required table re-creation
What part of the error do you not understand? When a column is added to an existing table, there are rows. The column is assigned to each of those rows. SQL Server has to give those rows a value. How does it do this?
It can assign the default value for the column.
It can assign NULL.
In your case, you have defined the column as NOT NULL but not provided a default value. Hence, the database does not know what to do, so it returns an error.
The simplest solution is to remove the NOT NULL constraint in the definition. Very close behind is assigning a default value.

How to specify a conditional DEFAULT constraint in SQL Server?

I am adding a column as a foreign key which cannot be NULL and so need to have a DEFAULT value.
ALTER TABLE location
ADD [retailer_brand_id] INT NOT NULL DEFAULT (SELECT retailer_id from retailer),
FOREIGN KEY(retailer_brand_id) REFERENCES retailer_brand(retailer_brand_id);
What I want to achieve is, get the retailer_id from SELECT retailer_id from retailer and if it is equal to 12 then set it to 0, otherwise set to the retailer_id returned by the select query.
When I use the above query, I get an error message
Subqueries are not allowed in this context. Only scalar expressions are allowed.
I recommend a calculated column instead....so you don't also have to have this case statement in application logic as well as the table definition...don't want it in 2 spots...and don't have to worry about when retailerid changes...calc column would take care of that
I needed similar functionality. Calculated column is not an option for me, since my value should be changeble later by user, so I went with trigger on insert.
Described for example here: Trigger to update table column after insert?

Change column value after INSERT if the value fits criteria?

I have never really worked with Triggers before in MSSQL but I think it'll be what I need for this task.
The structure of the table is as such:
ID|****|****|****|****|****|****|****|TOUROPERATOR
The Tour Operator Code is the code that tells us what company owned the flight we carried out for them. Two of those codes (there are 24 in total) are outdated. Our users requested that those two be changed but the tour operator code is pulled from a database we don't control. The FlightData table however, we do control. So I was thinking a trigger could change the tour operator code if it was one of the two outdated ones, to the correct ones instead respectively when they were inserted.
So I went into good ol' SQL Management Studio and asked to make a trigger. It gave me some sample code and here is my Pseudo Code below:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TRIGGER ChangeProvider
ON FlightData
AFTER INSERT
AS
BEGIN
IF(TheInsertedValue == Criteria)
UPDATE FlightData
SET TheInsertedValue = NewValue
ENDIF
END
GO
I am not that good with this type of Database Programming so excuse my mistakes.
How would I go about doing this?
You could add a computed column to your table instead of adding a trigger.
Then the new column could just use a case statement to either show
the original TourOperator column value or the new value you wanted.
You'd add a new column to your table like this
TourOperatorCorrect = CASE WHEN TourOperator = 'Whatever value' THEN 'ChangedValue'
--I just want to use what I have already in the TourOperator column
ELSE TourOperator
END AS VARCHAR(50)
Basics of computed columns are here - https://msdn.microsoft.com/en-ie/library/ms188300.aspx
Your misconception here is that the trigger runs once per inserted value - it is in fact run once per insert statement, so you can and will find more than one row inserted at once.
You'll find that your inserted values are in the pseudo table inserted, which has the same structure as your FlightData table in this case. You write a select statement against that, specifying any criteria you wish.
However, it's not immediately clear what your logic is - does the FlightData table you are updating in your trigger only have one row? Do you update every row in the table with the newest inserted value? It is hard to understand what you are trying to now, and what the purpose of the table and this trigger are - let alone what you would want to do if you inserted more than one row at once.
When inserted table contains mutiple rows,your code will fail,so change code to work with inserted table as whole
UPDATE F
SET f.TheInsertedValue = i.value
from inserted i
join
Flighttable F
on f.matchingcolumn=i.matchingcolumn
and i.somevalue='criteria'

Delete a specific field from a database

How can I delete the value of a field from a database, using query code? I only know where the field is located in the database. (ex: column['phone number']row[3])
It should be something like this "DELETE FROM ... WHERE ..."
There is nothing like delete the field in database i.e. if you want to remove the complete row then you can do that easily like this
DELETE FROM TABLE WHERE COLUMN1=#myValue
But if you wanted to remove one value of the row in that case you should update that value as NULL
UPDATE TABLE SET COLUMN1=NULL WHERE COLUMN1=#myValue
I have used where clause from my imagination. you can always use whatever you want.
The DELETE statement allows you to delete RECORDS.
When you want to set a field to an empty value, use the UPDATE statement.
See this for more info.
UPDATE [YOUR_TABLE] SET [YOUR_FIELD] = NULL WHERE [YOUR_PRIMARY_KEY] = VALUE
Yes first you need to use delete command. Then after this insert update command then only the records will be deleted from the database. I agree that you have deleted records but its not showing because you haven't updated it.

date syntax issue in sql

I keep getting this error message when trying to change the data type of my column:
alter table x modify column order_date date NOT NULL;
ERROR at line 1
ORA-00905 missing keyword
I not sure where I am going wrong, as I am aware there are many types of dates in sql?
Many thanks
The MODIFY clause does not take COLUMN as a keyword. This will work:
alter table x modify order_date date NOT NULL;
The syntax is documented in the Oracle SQL reference. Find out more.
We only need to include COLUMN with commands which have several different possibilities. For instance, with the ALTER TABLE ... DROP command, because we can drop columns, constraints or partitions....
alter table x drop column order_date ;
"when I tried entering NOT NULL, it said the table needed to be empty"
You should be able to apply a NOT NULL constraint, providing all the rows in the table have a value in the order_date column. The error message you get is quite clear:
ORA-01758 table must be empty to add mandatory (NOT NULL) column
This means your column has some rows without values. So, you need to update the table and populate those rows with some value; what you will use as a default depends on your business rules.