SQL trigger, check if certain value was entered - sql

INSERT INTO table_name (column1, column2, column3,...)
VALUES (value1, value2, value3,...)
Now what to check:
If inserted value1 = null, change it to 0
How to do it via trigger? I googled for examples and I have never ever done a trigger, so it is rather confusing.
So far got only this:
CREATE TRIGGER testTrigger
ON myTable
AFTER INSERT, UPDATE, DELETE

You can add default value . This is how it's done for a new column. For existing one you should add constraint. Check Update 2
ALTER TABLE table_name
ADD column1 int NOT NULL DEFAULT(0)
Add a column with a default value to an existing table in SQL Server
UPDATE:
To set default value, you should update NULL values at first.
UPDATE table_name
SET column1 = 0
WHERE column1 IS NULL
UPDATE 2:
Try adding constraint
ALTER TABLE table_name
ADD CONSTRAINT DF_column1 DEFAULT 0 FOR column1

You could write this in the trigger:
UPDATE T SET value1 =0
FROM table_name T
JOIN INSERTED I
ON T.<id>=I.<id>
WHERE I.value1 is null
INSERTED table which is accessible only within trigger will store the values that have inserted..

use ISNULL on the INSERTED value
SELECT ISNULL(INSERTED,0) FROM INSERTED

Related

How can I add prefix to SQLite auto_increment field?

Is there a way to add prefix to an auto increment field in SQLite so that when new records are added, the auto increment value contain the prefix?
Is there a way to add prefix to an auto increment field in sqlite so
that when new records are added, the auto increment value contain the
prefix?
No.
Such a column is a special column that is an alias of the rowid column. Such a column MUST be an integer value.
The intended use of such a column is really to be able to uniquely identify a row.
BUT.....
However, it would be possible to always return a value with a prefix e.g. by using
SELECT 'prefix'||mycolumn FROM mytable;
Working Example
:-
DROP TABLE IF EXISTS mytable;
CREATE TABLE IF NOT EXISTS mytable (mycolumn INTEGER PRIMARY KEY, myothercolumn TEXT);
INSERT INTO mytable (myothercolumn) VALUES('Fred'),('Mary'),('Jane'),('andsoon');
SELECT 'myprefix'||mycolumn, myothercolumn FROM mytable;
Note there is no need for the AUTOINCREMENT keyword that only imposes a constraint but is inefficient AUTOINCREMENT
Result
Mimicking what you want
It would be possible to replicate what you want e.g. :-
DROP TRIGGER IF EXISTS mytable2manager;
DROP TABLE IF EXISTS mytable2;
CREATE TABLE IF NOT EXISTS mytable2 (mycolumn TEXT, myothercolumn TEXT);
CREATE TRIGGER IF NOT EXISTS mytable2manager AFTER INSERT ON mytable2 BEGIN
UPDATE mytable2 SET mycolumn = 'myprefix'||(SELECT count() FROM mytable2) WHERE rowid = new.rowid;
END;
INSERT INTO mytable2 (myothercolumn) VALUES('Fred'),('Mary'),('Jane'),('andsoon');
SELECT * FROM mytable2;
This creates a table along with a TRIGGER and then inserts the same data as above.
The TRIGGER is actioned whenever a row is inserted and in this case it mimics what the SQLite auto-generation of the rowid value does prefixing the value
it could alternatively use SET mycolumn = 'myprefix'||rowid
Without the TRIGGER mycolumn would be null
Result
Additional
You could even have the TRIGGER in the mimicking method apply different prefixes. The following example uses a different prefix when the value in the myothercolumn starts with an M
:-
DROP TRIGGER IF EXISTS mytable2manager;
DROP TABLE IF EXISTS mytable2;
CREATE TABLE IF NOT EXISTS mytable2 (mycolumn TEXT, myothercolumn TEXT);
CREATE TRIGGER IF NOT EXISTS mytable2manager AFTER INSERT ON mytable2 BEGIN
UPDATE mytable2 SET mycolumn = CASE WHEN substr(new.myothercolumn,1,1) = 'M' THEN 'myprefix' ELSE 'myotherprefix' END||(SELECT count() FROM mytable2) WHERE rowid = new.rowid;
-- UPDATE mytable2 SET mycolumn = 'myprefix'||rowid WHERE rowid = new.rowid;
END;
INSERT INTO mytable2 (myothercolumn) VALUES('Fred'),('Mary'),('Jane'),('andsoon');
SELECT * FROM mytable2;
Result
The simplest method is probably to use a view:
create view v_t as
select ('prefix' || id) as new_id, t.*
from t;

In SQL, How to add values after add a new column in the existing table?

I created a table and inserted 3 rows. Then I added a new column using alter. How can I add values to the column without using any null values?
Two solutions.
Provide a default value for the column. This value will be used initially for all existing rows. The exact syntax depends on your database, but will will usually look like ..
this:
ALTER TABLE YourTable
ADD YourNewColumn INT NOT NULL
DEFAULT 10
WITH VALUES;
Add the column with null values first. Then update all rows to enter the values you want.
Like so:
ALTER TABLE YourTable
ADD YourNewColumn INT NULL;
UPDATE YourTable SET YourNewColumn = 10; -- Or some more complex expression
Then, if you need to, alter the column to make it not null:
ALTER TABLE YourTable ALTER COLUMN YourNewColumn NOT NULL;
Why don't you use UPDATE statement:
UPDATE tablename SET column=value <WHERE ...>
WHERE is optional. For instance in T-SQL for table:
I can update column NewTestColumn by this statement:
UPDATE [dbo].[Table] SET [NewTestColumn] = 'Some value'
Suppose you have a Employee table with these columns Employee_ID, Emp_Name,Emp_Email initially. Later you decide to add Emp_Department column to this table. To enter values to this column, you can use the following query :
Update *Table_Name* set *NewlyAddedColumnName*=Value where *Columname(primary key column)*=value
Example update TblEmployee set Emp_Department='Marketing' where Emp_ID='101'
I think below SQL useful to you
update table_name set newly_added_column_name = value;
update table_name
set new_column=value
Update table_name set column_name = value where 'condition';
suppose emp is the table and Comm is the new column then fire the below query .
update emp set Comm=5000
For Microsoft SQL (T-SQL):
UPDATE TABLE_NAME SET COLUMN_NAME=10;
here 10 means it will set all values by default to 10

Set value of the column to default for NULL values

I have a table with a column which has default value to 0. However when null is inserted to this table, I want it to set it to default.
As the insert query is generic and used by other databases too, I cannot make any changes to the insert statement.
Can I have constraints or case statement on create table, so that default 0 value is inserted whenever null is passed.
If you can not change an insert statement you have no way other then creating an instead of insert trigger:
CREATE TRIGGER trTableName
ON SchemaName.TableName
INSTEAD OF INSERT
AS
BEGIN
INSERT INTO TableName (ColumnA, ColumnB, ...)
SELECT ISNULL(ColumnA, 0), ISNULL(ColumnB, 0), ...
FROM INSERTED
END
You can do an update using a trigger on insert.
CREATE TRIGGER [dbo].[YourTriggerName]
ON [dbo].[YourTable]
AFTER INSERT
AS
BEGIN
UPDATE t SET YourCol = 0
FROM YourTable t
JOIN Inserted i ON t.Id = i.Id
WHERE i.YourCol IS NULL
END
Inserting null is the same as inserting a specific value, and so the default value is bypassed.
To use the default setting the insert statement shouldn't insert anything to this column.
If you can't use Coalesce (value, 0) in the select bit of the into statement, try using it in your select queries to disguise the result.

Populate extra database column depending on other column values

I have a database which collects data from an application. And now, I have to create another column that will be populated with predefined data depending on the values in other columns. So, no math, just to look up the values in two other columns and insert the data into the newly added column.
Example
id column1 column2 newColumn
1 15 3 100
So when column1 has 15, and column2 has 3, the newColumn should be auto-populated with 100. Again, the number 100 is predifned, not calcualted.
I know I can use triggers for new entries, but the database already has a large amount of data entered, so is there a way to auto populate the newColumn for data that is already tere?
EDIT --------------------------------
So I can use update to populate the column for the records that are already entered ?!
Can i make a trigger which will wait for both values and until both are entered it will return NULL?
You can create scalar function:
ALTER FUNCTION [dbo].[Test] ( #column1 INT, #column2 INT)
RETURNS INT
WITH SCHEMABINDING
AS
BEGIN
DECLARE #r INT
IF #column1 = 15 AND #column2 = 3
SET #r = 100
ELSE
SET #r = NULL
RETURN #r
END
And then add new computed column:
ALTER TABLE TableName ADD ColumnName AS dbo.Test(column1, column2) PERSISTED
Persisted means, that column is not calculated on the fly, but data is saved.
That's why you used WITH SCHEMABINDING. Without binding you can not make the column persisted.
You can also update your current data with simple update statement like in #Rhys Jones answer and add trigger on table like:
ALTER TRIGGER trTest ON TableName
AFTER INSERT, UPDATE
AS
BEGIN
IF UPDATE(column1) AND UPDATE(column2)
BEGIN
UPDATE TableName
SET NewColumn = CASE
WHEN column1 = 15 and column2 = 3 then 100
ELSE NULL
END
FROM Inserted i
JOIN TableName t ON t.id = i.id
END
END
You could just use a single UPDATE to update the missing values, then use the TRIGGER for new rows.
update MyTable set
newColumn = case
when column1 = 15 and column2 = 3 then 100
when ...
end
where
newColumn is null
However, note what #jarlh says above, there are usually better ways of doing this such as views or computed columns.

How to insert one column into other column within the same table in SQL Server

I need to insert one column's data into another column within the same table.
Can anybody tell me how to write this?
Thanks
UPDATE table
SET col_2 = col_1
If you want to copy data from one column to another on the same table:
UPDATE table_name SET
destination_column_name=orig_column_name
WHERE condition_if_necessary
IF you want to add a new column and copy the original data to that column:
ALTER TABLE table_name
ADD new_column_name column_type NULL
UPDATE table_name SET
destination_column_name=orig_column_name
WHERE condition_if_necessary
If you want the column to be non-nullable, then you can set it to a default value before doing the update.
begin transaction
alter table Song add SortArtist nvarchar(128) not null default N''
go
update Song set SortArtist = Artist
commit transaction
alter table [dbo].[GetPermission]
add username1 varchar(100) ----------------ading new column username1
update GetPermission set username1=username