Drop primary key and add in Transact-SQL - asp.net

I've researched and tried everything, I don't know if I'm missing something but here is my attempt at a dropping the primary key
Alter Table Course
Drop constraint PK_Course_CourseID
Go
Table name is Course and the PK is CourseID. I then need to re-add the PK constraint to column "row"

To delete a primary key constraint:
In Object Explorer, right-click the table with the primary key, and click Design.
The table opens in Table Designer.
In the table grid, right-click the row with the primary key and choose Remove Primary Key to toggle the setting from on to off.
Source:
https://msdn.microsoft.com/en-us/library/ms190621(v=sql.105).aspx

Drop primary key:
DECLARE #table NVARCHAR(512), #sql NVARCHAR(MAX);
SELECT #table = N'dbo.Course';
SELECT #sql = 'ALTER TABLE ' + #table
+ ' DROP CONSTRAINT ' + name + ';'
FROM sys.key_constraints
WHERE [type] = 'PK'
AND [parent_object_id] = OBJECT_ID(#table);
EXEC sp_executeSQL #sql;
Change previous column type (if was seed/auto-increment):
ALTER TABLE dbo.Course
ALTER COLUMN YourColumnName INT
Add PK
ALTER TABLE Course ADD PRIMARY KEY (id)
Hope this helps!

DECLARE #V_CONSTRAINTNAME NVARCHAR(256);DECLARE #V_QUERY NVARCHAR(1000);BEGINSELECT #V_CONSTRAINTNAME = constraint_name FROM INFORMATION_SCHEMA.table_constraints WHERE table_name = 'Course'AND constraint_type ='PRIMARY KEY';IF #V_CONSTRAINTNAME IS NOT NULL BEGINSET #V_QUERY = 'ALTER TABLE #DBNAME#.#USERNAME#.Course DROP CONSTRAINT '+ #V_CONSTRAINTNAME;exec sp_executesql #V_QUERY;END;ENDGO
DECLARE #V_COUNT INT;BEGINSET #V_COUNT = 0;SELECT #V_COUNT = COUNT(*) FROM INFORMATION_SCHEMA.table_constraints WHERE TABLE_NAME = 'Course' AND CONSTRAINT_TYPE = 'PRIMARY KEY';IF #V_COUNT = 0BEGINEXEC SP_EXECUTESQL N'ALTER TABLE #DBNAME#.#USERNAME#.Course ADD CONSTRAINT PK_Course_CourseID PRIMARY KEY (row)';END;END;GO

Related

Insert the id from a previous query inside a sqlite trigger

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

Cannot insert data in trigger

It give me error example image at below:
Trigger code:
CREATE OR REPLACE TRIGGER InsertNewStaffs
BEFORE INSERT ON Staffs
FOR EACH ROW
ENABLE
DECLARE
v_user varchar(255);
v_date varchar(255);
v_Staffs_ID Staffs.Staffs_ID%TYPE;
v_Staffs_Name Staffs.Staffs_Name%TYPE;
v_Staffs_Contact_Number Staffs.Staffs_Contact_Number%TYPE;
v_Staffs_Email Staffs.Staffs_Email%TYPE;
v_Orders_ID Staffs.Orders_ID%TYPE;
v_count INTEGER;
BEGIN
SELECT count(*) INTO v_count FROM Staffs
WHERE Staffs_ID = v_Staffs_ID OR
Staffs_Name = v_Staffs_Name OR
Staffs_Contact_Number = v_Staffs_Contact_Number OR
Staffs_Email = v_Staffs_Email;
IF v_count > 0 THEN
RAISE_APPLICATION_ERROR(-20000, 'Oops, some data is already exists. Please try again...');
DBMS_OUTPUT.PUT_LINE('Oops, some data is already exists. Please try again...');
SELECT user, TO_CHAR(sysdate, 'DD/MON/YYYY HH24:MI:SS') INTO v_user, v_date FROM dual;
ELSE
INSERT INTO Staffs(Staffs_ID, Staffs_Name, Staffs_Contact_Number, Staffs_Email, Orders_ID)
VALUES(v_Staffs_ID, v_Staffs_Name, v_Staffs_Contact_Number, v_Staffs_Email, v_Orders_ID);
DBMS_OUTPUT.PUT_LINE('One Row Inserted By ' || v_user || CHR(10));
DBMS_OUTPUT.PUT_LINE('Inserted data at ' || v_date);
INSERT INTO monitorInsertStaffs(user_name, entry_date, operation)
VALUES(v_user, v_date, 'Insert');
END IF;
END;
/
My Table:
CREATE TABLE Staffs(
Staffs_ID char(20) NOT NULL,
Staffs_Name varchar(255) NOT NULL,
Staffs_Contact_Number varchar(50) NOT NULL,
Staffs_Email varchar(255) NOT NULL,
Orders_ID char(20),
PRIMARY KEY (Staffs_ID),
FOREIGN KEY (Orders_ID) REFERENCES Orders(Orders_ID)
);
CREATE TABLE Orders(
Orders_ID char(20) NOT NULL,
Order_Date DATE NOT NULL,
Order_Status varchar(255) NOT NULL,
Order_Quantity int NOT NULL,
Order_TotalAmount NUMERIC(10,2) NOT NULL,
Order_TotalPrice NUMERIC(10,2) NOT NULL,
PRIMARY KEY (Orders_ID),
Pets_Products_ID char(20),
CustomerID char(20),
FOREIGN KEY (Pets_Products_ID) REFERENCES Pets_Products(Pets_Products_ID),
FOREIGN KEY (CustomerID) REFERENCES Customers(CustomerID)
);
I try to insert data and if the data has existed it will show RAISE_APPLICATION_ERROR(-20000, 'Oops, some data is already exists. Please try again...'); but it didn't show the message and also cannot insert data when no exists the data.
I don't know where is error code that I find.
The whole concept is just wrong.
you've based trigger on a table into which you're just inserting a row (staffs)
then you're selecting from the same table (it'll raise the mutating table error if you try to insert more than a single row)
the where clause uses local variables that have no values
insert into staffs cause the same trigger to fire over and over again, until Oracle concludes that that's enough and raises the error
Don't use a trigger. Use UNIQUE constraints:
CREATE TABLE Staffs(
Staffs_ID char(20) NOT NULL,
Staffs_Name varchar(255) NOT NULL,
Staffs_Contact_Number varchar(50) NOT NULL,
Staffs_Email varchar(255) NOT NULL,
Orders_ID char(20),
PRIMARY KEY (Staffs_ID),
UNIQUE (Staffs_Name),
UNIQUE (Staffs_Contact_Number),
UNIQUE (Staffs_Email),
FOREIGN KEY (Orders_ID) REFERENCES Orders(Orders_ID)
);
(However, you should also consider whether your business requirements make sense or if you can have multiple staff members called Jane Smith or if you can have two staff members who share an office with the same telephone number?)
If you want to use a logging table then use an autonomous transaction to just insert into that table:
CREATE OR REPLACE TRIGGER InsertNewStaffs
BEFORE INSERT ON Staffs
FOR EACH ROW
ENABLE
DECLARE
PRAGMA AUTONOMOUS_TRANSACTION;
BEGIN
INSERT INTO monitorInsertStaffs(
user_name, entry_date, operation
) VALUES(
:NEW.Staffs_ID, SYSDATE, 'Insert'
);
COMMIT;
END;
/
db<>fiddle here

Refer to an other table's column in a trigger?

Given:
CREATE TABLE worktags (
worktag_id integer not null primary key,
worktag character(32) not null default '' unique,
...
last_updated character(32) not null default '[Error]'
);
CREATE TABLE truefacts (
about character(32) not null primary key,
fact character(32) not null
);
The following:
CREATE TRIGGER zz_worktags_last_updated AFTER UPDATE ON worktags BEGIN
UPDATE worktags SET
last_updated = truefacts.fact WHERE truefacts.about = 'Last Worktag Update';
END;
gives the error:
Error: near line 52: no such column: truefacts.fact
But the column exists, and the syntax diagram seems to indicate that
[[schema-name . ] table-name . ] column-name
is a legal expr for the right-side of a SET column-name = expr.
You would need to use a subquery to access the other (truefacts) table (as there is no FROM truefacts anywhere) e.g. :-
CREATE TRIGGER zz_worktags_last_updated AFTER UPDATE ON worktags BEGIN
UPDATE worktags SET
last_updated = (SELECT fact FROM truefacts WHERE about = 'Last Worktag Update');
END;
Saying that, there is then no need for the TRIGGER as the subquery could be embedded into the UPDATE.
e.g. consider the following example :-
DROP TRIGGER IF EXISTS zz_worktags_last_updated;
DROP TABLE IF EXISTS worktags;
DROP TABLE IF EXISTS truefacts;
CREATE TABLE worktags (
worktag_id integer not null primary key,
worktag character(32) not null default '' unique,
last_updated character(32) not null default '[Error]'
);
CREATE TABLE truefacts (
about character(32) not null primary key,
fact character(32) not null
);
INSERT INTO truefacts VALUES('Last Worktag Update','xxx');
INSERT INTO worktags (worktag,last_updated) VALUES('mytag',(datetime('now')));
SELECT * FROM worktags;
UPDATE worktags SET last_updated = (SELECT fact FROM truefacts WHERE about = 'Last Worktag Update'), worktag = 'aaaa' WHERE worktag_id = 1;
SELECT * FROM worktags;
UPDATE truefacts SET fact = 'zzzz' WHERE rowid = 1;
CREATE TRIGGER zz_worktags_last_updated AFTER UPDATE ON worktags BEGIN
UPDATE worktags SET
last_updated = (SELECT truefacts.fact FROM truefacts WHERE truefacts.about = 'Last Worktag Update');
END;
UPDATE worktags SET worktag = 'bbbb' WHERE worktag_id = 1;
SELECT * FROM worktags;
This :-
Drops the tables and triggers if they exist (so it can be rerun)
Crate the 2 tables and populates them.
Selects everything from the worktags table (just the 1 row)
Updates the row in the worktags table using a subquery (this is the no trigger required example)
Selects everything from the updated (without a trigger) worktags table.
Updates the fact column of the truefacts (to show that the trigger works)
6.Creates the trigger.
Updates the row in the worktags table, changing the worktag column, leaving the change to the last_updated column to be done by the trigger.
Selects everything from the updated by the trigger worktags table.
Running the above results in :-
and lastly

ssdt: change the types of primary key/secondary keys

Original table1 and Table2. Both tables has data.
CREATE TABLE [dbo].[Table1]
(
[Id] int NOT NULL PRIMARY KEY
)
CREATE TABLE [dbo].[Table2]
(
[Id] INT NOT NULL PRIMARY KEY,
[Table1Id] Int NULL,
Constraint [FK_Table1_Table2] foreign key ([Table1Id]) references [Table1] (Id)
)
I'd like to change the Table1.Id to UNIQUEIDENTIFIER.
Obviously just jump in and change the type from int to UNIQUEIDENTIFIER for Table1.Id and 'Table2.Table1Id'. Then Publish. Here is the code:
CREATE TABLE [dbo].[tmp_ms_xx_Table1] (
[Id] UNIQUEIDENTIFIER NOT NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);
IF EXISTS (SELECT TOP 1 1
FROM [dbo].[Table1])
BEGIN
INSERT INTO [dbo].[tmp_ms_xx_Table1] ([Id])
SELECT [Id]
FROM [dbo].[Table1]
ORDER BY [Id] ASC;
END
This code will fail because original Table1.Id is Int while temp table Id is UNIQUEIDENTIFIER.
Then, I try to with Pre-Scripts. Ideally all the changes will be done manually.
--drop fk constraint
alter table [Table2] drop constraint [FK_Table1_Table2];
--rename table1.id
exec sp_rename 'Table1.Id', 'Id2', 'COLUMN';
alter table [Table1] add Id uniqueidentifier not null
default newid();
--rename table2.table1id
exec sp_rename 'Table2.Table1Id', 'Table1Id2', 'COLUMN';
alter table [Table2] add Table1Id uniqueidentifier null;
update t2 set t2.Table1ID = t1.Id
from Table2 t2 left join Table1 t1 on t2.Table1Id2 = t1.Id2;
alter table [Table2] add constraint [FK_Table1_Table2] foreign key (Table1Id) references Table1 (Id);
However it FAIL again as SSDT is trying to compare its data structure again the target database.
Any idea please?
You're right. The problem is that you can't include schema changes in the pre-deployment script because SSDT's deployment script is generated prior to your schema changes. It is therefore only useful for data-only changes.
The solution is to do this outside of the SSDT process altogether. Yes, it's a pre-pre-deployment script! Essentially you have to apply your change by yourself before you even get to the SSDT bit.
(There's probably a way to do this via a custom deployment contributor. After all, everything is possible in code...)
Can I convince you to take a look at a migration-based solution as it appears that you have sufficient need for an element of fine-grained script "customisation". DBUp is a popular open source solution. ReadyRoll is a more-integrated commercial solution that shares a lot with SSDT.
the problem is the old data. it will be ok without the data in table in step 2.
1.pre-script: copy/process old data to temp tables, delete them from original tables
create table #table1 (
id int null,
id2 uniqueidentifier null
);
insert into #table1 (id,id2)
select id,newid() from Table1;
create table #table2 (
id int null,
table1id int null,
table1id2 uniqueidentifier null
);
insert into #table2 (id, table1id)
select id,table1id from Table2;
update t2 set t2.table1id2=t1.id2
from #table2 t2 left join #table1 t1 on t2.table1id = t1.id;
delete from table2;
delete from table1;
dacpac will auto generate the changes for schema. it will be ok because no data is existing any more.
post-script: insert data back from temp tables in pre-script:
insert into table1 (id)
select id2 from #table1;
insert into table2 (id,table1id)
select id, table1id2 from #table2;

Use trigger for auto-increment

I'm trying to solve the problem that composite keys in sqlite don't allow autoincrement.
I don't know if it's possible at all, but I was trying to store the last used id in a different table, and use a trigger to assign the next id when inserting a new reccord.
I have to use composite keys, because a single pk wouldn't be unique (because of database merging).
How can I set a field of the row being inserted based on a value in a different table
The query so far is:
CREATE TRIGGER pk BEFORE INSERT ON product_order
BEGIN
UPDATE auto_increment SET value = value + 1 WHERE `table_name` = "product_order";
END
This successfully updates the value. But now I need to assign that new value to the new record. (new.id).
If you use an AFTER INSERT trigger then you can update the newly inserted row, as in the following example.
CREATE TABLE auto_increment (value INT, table_name TEXT);
INSERT INTO auto_increment VALUES (0, 'product_order');
CREATE TABLE product_order (ID1 INT, ID2 INT, name TEXT);
CREATE TRIGGER pk AFTER INSERT ON product_order
BEGIN
UPDATE auto_increment
SET value = value + 1
WHERE table_name = 'product_order';
UPDATE product_order
SET ID2 = (
SELECT value
FROM auto_increment
WHERE table_name = 'product_order')
WHERE ROWID = new.ROWID;
END;
INSERT INTO product_order VALUES (1, NULL, 'a');
INSERT INTO product_order VALUES (2, NULL, 'b');
INSERT INTO product_order VALUES (3, NULL, 'c');
INSERT INTO product_order VALUES (4, NULL, 'd');
SELECT * FROM product_order;

Resources