Created two tables in two different database(TestDb1 and TestDb2) in the same server.I wrote after delete trigger on "Error_Master" table`.if i delete record in "ERROR_MASTER" table which is in TestDB1 that trigger insert records in "ERROR_MASTER_LOG" table which exists in TestDb2.
My dblink->dblink('dbname=TestDb2 port=5432 host=192.168.0.48 user=postgres password=soft123')
DB->TestDb1
CREATE TABLE public."ERROR_MASTER"
(
"MARKERID" integer NOT NULL,
"FILENAME" character varying,
"RECNO" integer,
"ERRORCODE" character varying,
"USERID" character varying,
"ID" integer NOT NULL,
CONSTRAINT "ERR_MASTER_pkey" PRIMARY KEY ("ID")
)
WITH (
OIDS=FALSE
);
DB->TestDb2
CREATE TABLE public."ERROR_MASTER_LOG"
(
"MARKERID" integer NOT NULL,
"FILENAME" character varying,
"RECNO" integer,
"ERRORCODE" character varying,
"USERID" character varying,
"ID" integer NOT NULL,
CONSTRAINT "ERR_MASTER_Log_pkey" PRIMARY KEY ("ID"),
"Machine_IP" character varying,
"DELETED_AT" timestamp
)
WITH (
OIDS=FALSE
);
ALTER TABLE public."ERROR_MASTER_LOG"
OWNER TO postgres;
GRANT ALL ON TABLE public."ERROR_MASTER_LOG" TO postgres;
CREATE INDEX "IDX_ERROR_MASTER_LOG_MARKERID_RECNO"
ON public."ERROR_MASTER_LOG"
USING btree
("MARKERID" COLLATE pg_catalog."default", "RECNO" COLLATE pg_catalog."default", round("X1"::numeric, 2));
i tried below trigger in TestDb1 for inserting record in a table which exists in another database TestDb2 using dblink. It shows schema "old" does not exist.Please help.
CREATE OR REPLACE FUNCTION mdp_error_master_after_delete()
RETURNS trigger AS
$BODY$
BEGIN
perform dblink_connect('host=localhost user=postgres password=postgres dbname=TestDB2');
perform dblink_exec('INSERT INTO "ERROR_MASTER_LOG"("MARKERID","ID")
values('||OLD."MARKERID"||','||OLD."ID"')');
perform dblink_disconnect();
RETURN OLD;
EXCEPTION WHEN OTHERS THEN
RAISE NOTICE 'insert_new_sessions SQL ERROR: %', SQLERRM;
RETURN NULL;
END;
$BODY$
LANGUAGE plpgsql VOLATILE
COST 100;
ALTER FUNCTION mdp_error_master_after_delete()
OWNER TO postgres;
CREATE TRIGGER ERROR_MASTER_CHANGES
AFTER DELETE
ON "ERROR_MASTER"
FOR EACH ROW
EXECUTE PROCEDURE mdp_error_master_after_delete()
Related
In a sqlite3 database I would like to create a trigger on a view so that I can insert data over the view. Inside the trigger I would like to insert something in the tblmedia table. The id of the inserted row should be now also inserted into the tblbook as id.
In sqlite there are no variables. Otherwise I would store the returning value in the variable and would use it in the second query.
Can this even be achieved in sqlite?
Following my sql schema:
CREATE TABLE tblmedia(
id INTEGER PRIMARY KEY NOT NULL,
title VARCHAR NOT NULL,
raiting INTEGER,
file_name VARCHAR NOT NULL,
media_type TEXT NOT NULL
);
CREATE TABLE tblbook(
id INTEGER PRIMARY KEY NOT NULL,
author VARCHAR,
FOREIGN KEY (id) REFERENCES tblmedia(id) ON DELETE CASCADE
);
CREATE VIEW book AS
SELECT
m.id as id,
m.title as title,
b.author as author,
m.raiting as raiting,
m.file_name as file_name
FROM tblbook b
LEFT JOIN tblmedia m ON m.id = b.id;
CREATE TRIGGER insert_book
INSTEAD OF INSERT ON book
BEGIN
INSERT INTO tblmedia(title, raiting, file_name)
VALUES(new.title, new.raiting, new.file_name);
INSERT INTO tblbook(id, author)
VALUES (xx, new.author); -- xx should be the id from the previous insert
END
I have 2 tables CarParking and ParkingArea. On ParkingArea I need to save the MaxPricePerDay, and on CarParking I have to save the cost. I try to write constraint that the cost is under or equal to MaxPricePerDay base on the AID columnn.
How can I do that?
CREATE TABLE "CarParking" (
"StartTime" TIMESTAMP NOT NULL,
"EndTime" TIMESTAMP NOT NULL,
"Cost" INTEGER NOT NULL,
"CID" INTEGER NOT NULL,
"AID" INTEGER NOT NULL,
FOREIGN KEY("CID") REFERENCES "Car"("CID")
ON DELETE CASCADE,
FOREIGN KEY("AID") REFERENCES "ParkingArea"("AID")
ON DELETE SET NULL,
CONSTRAINT time_car CHECK(StartTime<=EndTime),
PRIMARY KEY("StartTime","CID")
);
CREATE TABLE "ParkingArea" (
"MaxPricePerDay" INTEGER NOT NULL,
"PricePerHour" INTEGER NOT NULL,
"Name" TEXT NOT NULL,
"AID" INTEGER UNIQUE NOT NULL,
"Neighborhood" INTEGER NOT NULL,
PRIMARY KEY("AID"),
FOREIGN KEY ("Neighborhood") REFERENCES "Neighborhood" ("NID")
ON DELETE CASCADE
);
Since CHECK constraints can't have subqueries, one way is using a trigger instead.
CREATE TRIGGER check_max_price BEFORE INSERT ON CarParking
BEGIN
SELECT raise(ABORT, 'Exceeded MaxPricePerDay')
FROM ParkingArea
WHERE aid = new.aid AND new.Cost > MaxPricePerDay;
END;
is a starting point; you'll have to tweak the calculation to see if the cost is too much as appropriate.
If your cost can be updated after a row is inserted, you'll want a similar trigger for UPDATE.
I'm creating a SQLite database with this Knex migration. When I review the DB in SQLiteStudio, it doesn't indicate that the email column is unique. Is there a mistake I'm missing?
exports.up = function (knex) {
return knex.schema
.createTable('users', users => {
users.increments();
users.string('email', 128).unique().notNullable();
users.string('password', 256).notNullable();
})
Generated DDL code:
CREATE TABLE users (
id INTEGER NOT NULL
PRIMARY KEY AUTOINCREMENT,
email VARCHAR (128) NOT NULL,
password VARCHAR (256) NOT NULL
);
Alternatives I've tried that didn't work:
-Switching order of unique() and notNullable()
users.string('email', 128).notNullable().unique()
-Creating a separate line to add the Unique constraint
.createTable('users', users => {
users.increments();
users.string('email', 128).notNullable();
users.string('password', 256).notNullable();
users.unique('email');
})
It's unique, you're just not going to see it in the CREATE TABLE statement. SQLite sets a UNIQUE constraint by creating an index with the UNIQUE qualifier. Take the following Knex migration, for example:
exports.up = knex =>
knex.schema.debug().createTable("users", t => {
t.increments("id");
t.string("name").unique();
});
Note debug(), very handy if you want to see what SQL is being generated. Here's the debug output:
[
{
sql: 'create table `users` (`id` integer not null ' +
'primary key autoincrement, `name` ' +
'varchar(255))',
bindings: []
},
{
sql: 'create unique index `users_name_unique` on `users` (`name`)',
bindings: []
}
]
As you can see, a second statement is issued to create the UNIQUE constraint. If we now go and look at the database, we'll see something like:
07:48 $ sqlite3 dev.sqlite3
sqlite> .dump users
BEGIN TRANSACTION;
CREATE TABLE `users` (`id` integer not null primary key autoincrement,
`name` varchar(255));
CREATE UNIQUE INDEX `users_name_unique` on `users` (`name`);
COMMIT;
As an aside, you may wish to do more research about the possible length of user emails. See this answer as a starting point.
I am using asp.net2008 and MY SQL.
I want to auto-generate the value for the field username with the format as
"SISI001", "SISI002",
etc. in SQL whenever the new record is going to inserted.
How can i do it?
What can be the SQL query ?
Thanks.
Add a column with auto increment integer data type
Then get the maximum value of that column in the table using "Max()" function and assign the value to a integer variable (let the variable be 'x').
After that
string userid = "SISI";
x=x+1;
string count = new string('0',6-x.ToString().length);
userid=userid+count+x.ToString();
Use userid as your username
Hope It Helps. Good Luck.
PLAN A>
You need to keep a table (keys) that contains the last numeric ID generated for various entities. This case the entity is "user". So the table will contain two cols viz. entity varchar(100) and lastid int.
You can then have a function written that will receive the entity name and return the incremented ID. Use this ID concatenated with the string component "SISI" to be passed to MySQL for insertion to the database.
Following is the MySQL Table tblkeys:
CREATE TABLE `tblkeys` (
`entity` varchar(100) NOT NULL,
`lastid` int(11) NOT NULL,
PRIMARY KEY (`entity`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
The MySQL Function:
DELIMITER $$
CREATE FUNCTION `getkey`( ps_entity VARCHAR(100)) RETURNS INT(11)
BEGIN
DECLARE ll_lastid INT;
UPDATE tblkeys SET lastid = lastid+1 WHERE tblkeys.entity = ps_entity;
SELECT tblkeys.lastid INTO ll_lastid FROM tblkeys WHERE tblkeys.entity = ps_entity;
RETURN ll_lastid;
END$$
DELIMITER ;
The sample function call:
SELECT getkey('user')
Sample Insert command:
insert into users(username, password) values ('SISI'+getkey('user'), '$password')
Plan B>
This way the ID will be a bit larger but will not require any extra table. Use the following SQL to get a new unique ID:
SELECT ROUND(NOW() + 0)
You can pass it as part of the insert command and concatenate it with the string component of "SISI".
I am not an asp.net developer but i can help you
You can do something like this...
create a sequence in your mysql database as-
CREATE SEQUENCE "Database_name"."SEQUENCE1" MINVALUE 1 MAXVALUE 9999999999999999999999999999 INCREMENT BY 001 START WITH 21 CACHE 20 NOORDER NOCYCLE ;
and then while inserting use this query-----
insert into testing (userName) values(concat('SISI', sequence1.nextval))
may it help you in your doubt...
Try this:
CREATE TABLE Users (
IDs int NOT NULL IDENTITY (1, 1),
USERNAME AS 'SISI' + RIGHT('000000000' + CAST(IDs as varchar(10)), 4), --//getting uniqueness of IDs field
Address varchar(150)
)
(not tested)
I have created one table in oracle data base my table script is
CREATE TABLE wsc_widget_bundle (
id VARCHAR (50),
widgetBundle BLOB NULL,
devicesoftwareclass VARCHAR(30) NOT NULL,
widgetProfileId VARCHAR (50) NOT NULL,
bundleHash BLOB NULL,
widgetLocale VARCHAR (6) NOT NULL ,
status INT,
primary key(id),
unique(widgetProfileId, devicesoftwareclass,status),
foreign key(widgetProfileId) references wsc_widget_profile(id)
);
When i create ddl for that is looks like
create table "DEV1"."WSC_WIDGET_BUNDLE"(
"ID" VARCHAR2(50) not null,
"WIDGETBUNDLE" BLOB,
"DEVICESOFTWARECLASS" VARCHAR2(30) not null,
"WIDGETPROFILEID" VARCHAR2(50) not null,
"BUNDLEHASH" BLOB,
"WIDGETLOCALE" VARCHAR2(6) not null,
"STATUS" NUMBER,
constraint "SYS_C00323290" primary key ("ID")
);
alter table "DEV1"."WSC_WIDGET_BUNDLE"
add constraint "SYS_C00323292"
foreign key ("WIDGETPROFILEID")
references "MTP440_DEV1"."WSC_WIDGET_PROFILE"("ID");
create unique index "MTP440_DEV1"."SYS_C00323290" on "MTP440_DEV1"."WSC_WIDGET_BUNDLE"("ID");
create unique index "MTP440_DEV1"."SYS_C00323291" on "MTP440_DEV1"."WSC_WIDGET_BUNDLE"("WIDGETPROFILEID","DEVICESOFTWARECLASS","STATUS");
create index "MTP440_DEV1"."TEST" on "MTP440_DEV1"."WSC_WIDGET_BUNDLE"("DEVICESOFTWARECLASS","STATUS","WIDGETLOCALE","WIDGETPROFILEID");
Now i want to write alter script to alter unique key constrain of my table but as at creation of table I didn't mention the name of my unique key name it is given by system like SYS_C00323291
So how can I write alter script to drop that unique key whose name is not known to me and generation new one
You can find the name of the constraint by querying the user_constraints and user_cons_columns views.
Alter table x
drop constraint pk;
Alter table x
add constraint New_constraint_name PRIMARY KEY (colname);