Sqlite database with single row - sql

I want to create a sqlite database table having single row and multiple columns.
Each time entire row will be updated.
In the sqlite i can create the table but first time updating entire row is not working.
The update entire row works only after the first INSERT command. Instead of doing first time INSERT command is it possible to execute UPDATE command as soon as the table is created?
I am doing following steps:
$ sqlite3 test.db
sqlite> create table company (Id int primary key not null, name text, age int);
sqlite> update company set id=1, name='test', age=30;
sqlite> select * from company;
sqlite>
Here select statement is not returning anything.
Is there any restriction in SQL to use the UPDATE command very beginning?

You seem to be ignoring how sql works. You perform an update of nothing and expect that a row magically exists after that.
You have to do an insert first.

You want to try
insert into company values (1, 'test', 30);
in order to have one record.
update only changes what is alread there, it cannot be used to create (that is: insert) new records.
Now, after having created your first record, you can change it with a
update company set age = 45 where id = 1;

Related

When inserting a new row in table A, another row also gets inserted in table B

So I am working with these two tables, Dependency and DependencyList.
I am trying to write an SQL query that, when a new row gets created in table Dependencies, another one also gets created in DependencyList, having the DependencyId filled with the Id of the newly created Dependency.
The Id column of both tables is auto-incremented.
Would that be possible, in any way?
You would typically do this with a FOR INSERT trigger. You can access the previously generated id using the inserted pseudo-table.
CREATE TRIGGER myTrigger ON Dependencies FOR INSERT
AS INSERT INTO DependencyList (DependencyId) SELECT Id FROM inserted;
Demo on DB Fiddlde
You can also do this with two insert statements, using SCOPE_IDENTITY() to retrieve the last insert id:
INSERT INTO Dependencies(isResolved, AssignedToTaskId) VALUES(0, 0);
INSERT INTO DependencyList (DependencyId) SELECT SCOPE_IDENTITY();
Demo

Inserting Data from one table into another table but in a different database

I have two databases that contain all the same tables. So i am trying to copy data from one table in one database to the same table in the other database.
I am getting this error 'There is already an object named 'PayComponents' in the database.'
Not sure of another way to achieve what i want
SELECT * INTO [PSD2394].DBO.PayComponents
FROM [PSD1346].DBO.PayComponents
WHERE PCompID != 1 AND PCompID != 2
Expected Result - All records from DB - PSD1346 except where the PCompID = 1 and 2 are inserted into the PayComponents table in DB - PSD2394
SELECT INTO will create a new table each time, if that is what you want then you need to drop that table first.
To append in an existing table, you need to use the INSERT INTO SELECT for that, like this example
INSERT * INTO [PSD2394].DBO.PayComponents (column names...)
SELECT pc.column names...
FROM [PSD1346].DBO.PayComponents pc
WHERE pc.PCompID != 1
AND pc.PCompID != 2
If the primary key of [PSD2394].DBO.PayComponents is an identity field, you cannot copy it, because the database will not allow you to write an own value in an identity field.
In case you really need that, try this
SET IDENTITY_INSERT [PSD2394].DBO.PayComponents ON
do the insert statement here...
SET IDENTITY_INSERT [PSD2394].DBO.PayComponents OFF

Trigger: How does the inserted table work? How to access its rows?

I have the following table
Data --Table name
ID -- Identity column
PCode -- Postal Code
I created the following trigger:
CREATE TRIGGER Trig
ON Data
FOR INSERT
AS
BEGIN
Select * from inserted
END
And inserted the following values
INSERT INTO Data VALUES (125)
INSERT INTO Data VALUES (126)
INSERT INTO Data VALUES (127)
It shows this:
But I was expecting something like this:
After the 1st insertion, the trigger is executed -> one row is shown in the inserted table.
After the 2nd insertion, the trigger is executed -> two rows are shown in the inserted table.
After the 3rd insertion, the trigger is executed -> three rows are shown in the inserted table.
According to msdn.microsoft all the rows inserted are in this table.
How can I access the inserted table so that I can see all the expected rows and not separately?
You can not. From the Use the inserted and deleted Tables article on microsoft.com, you can read:
The inserted table stores copies of the affected rows during INSERT and UPDATE statements.
That means that the inserted table will only contain rows for the current INSERT or UPDATE statement.
If you do want to see all rows for several such INSERT or UPDATE statements, you will have to store these rows in a table you created yourself.
There are 2 table available in a trigger, the inserted and the deleted. Each update on table XXX is actually a delete row X from XXX then an insert of row X in table XXX. So the inserted inside the trigger is a copy of what got inserted. You can do a lot with a trigger, but triggers are dangerous.
For example, on a performance gig, I found a huge SP being run by a trigger, we dropped it and the database came back online. Or another example, if you do a trigger wrong to audit logins, you can down the server.
As TT mentioned, if you want to see all the inserted records then you need to change your Trigger to something like this:
CREATE TRIGGER Trig
ON Data
FOR INSERT
AS
BEGIN
Select * into "tablename"
from
(Select * from inserted) Ins
END

Trigger - After insert and delete example

I have a requirement as a trigger should get fired when any row is inserted or deleted from table FAB which contains num as unique value. and depending upon that num value, another table should be update.
e.g.
FAB table
num code trs
10 A2393 80
20 B3445 780
Reel table
reelnr num use flag
340345 10 500 1
when num 10 from FAB table gets deleted(or any new num gets inserted), the trigger should get fired and should check the reel table which contains that num value and give the reelnr.
How to proceed with this?
you can Use Inserted & Deleted Table in SQL
These two tables are special kind of table that are only available inside the scope of the triggers.
If you tries to use these tables outside the scope of Triggers then you will get Error.
Inserted : These table is use to get track of any new records that are insert in the table.
Suppose there are Six rows are inserted in your table then these table will consist of all the six rows that are inserted.
Deleted : These table is used to track all the Deleted record from your tables.
Last delete rows will be tracked by these table.
For Insert :
CREATE TRIGGER TR_AUDIT_Insert
ON Reel_table
FOR INSERT
AS
BEGIN
INSERT INTO Reel_table (reelnr, num, use, flag)
SELECT
reelnr,
num,
use,
flag
FROM
INSERTED
END
For Delete :
CREATE TRIGGER TR_AUDIT_Delete
ON Product
FOR DELETED
AS
BEGIN
INSERT INTO Reel_table (reelnr, num, use, flag)
SELECT
reelnr,
num,
use,
flag
FROM
DELETED
END
Note :
I don't know from where these three reelnr, use flag values you are getting
So, Please modify this as per your need.
This is the format of the Triggers that normally we use.
You also can do this by using single trigger also
I dont know what is your exact requirement
If you want to achieve by only single Trigger then you can refer this link :
Refer

Retrieve inserted row ID in SQL

How do I retrieve the ID of an inserted row in SQL?
Users Table:
Column | Type
--------|--------------------------------
ID | * Auto-incrementing primary key
Name |
Age |
Query Sample:
insert into users (Name, Age) values ('charuka',12)
In MySQL:
SELECT LAST_INSERT_ID();
In SQL Server:
SELECT SCOPE_IDENTITY();
In Oracle:
SELECT SEQNAME.CURRVAL FROM DUAL;
In PostgreSQL:
SELECT lastval();
(edited: lastval is any, currval requires a named sequence)
Note: lastval() returns the latest sequence value assigned by your session, independently of what is happening in other sessions.
In SQL Server, you can do (in addition to the other solutions already present):
INSERT INTO dbo.Users(Name, Age)
OUTPUT INSERTED.ID AS 'New User ID'
VALUES('charuka', 12)
The OUTPUT clause is very handy when doing inserts, updates, deletes, and you can return any of the columns - not just the auto-incremented ID column.
Read more about the OUTPUT clause in the SQL Server Books Online.
In Oracle and PostgreSQL you can do this:
INSERT INTO some_table (name, age)
VALUES
('charuka', 12)
RETURNING ID
When doing this through JDBC you can also do that in a cross-DBMS manner (without the need for RETURNING) by calling getGeneratedKeys() after running the INSERT
I had the same need and found this answer ..
This creates a record in the company table (comp), it the grabs the auto ID created on the company table and drops that into a Staff table (staff) so the 2 tables can be linked, MANY staff to ONE company. It works on my SQL 2008 DB, should work on SQL 2005 and above.
===========================
CREATE PROCEDURE [dbo].[InsertNewCompanyAndStaffDetails]
#comp_name varchar(55) = 'Big Company',
#comp_regno nchar(8) = '12345678',
#comp_email nvarchar(50) = 'no1#home.com',
#recID INT OUTPUT
-- The '#recID' is used to hold the Company auto generated ID number that we are about to grab
AS
Begin
SET NOCOUNT ON
DECLARE #tableVar TABLE (tempID INT)
-- The line above is used to create a tempory table to hold the auto generated ID number for later use. It has only one field 'tempID' and its type INT is the same as the '#recID'.
INSERT INTO comp(comp_name, comp_regno, comp_email)
OUTPUT inserted.comp_id INTO #tableVar
-- The 'OUTPUT inserted.' line above is used to grab data out of any field in the record it is creating right now. This data we want is the ID autonumber. So make sure it says the correct field name for your table, mine is 'comp_id'. This is then dropped into the tempory table we created earlier.
VALUES (#comp_name, #comp_regno, #comp_email)
SET #recID = (SELECT tempID FROM #tableVar)
-- The line above is used to search the tempory table we created earlier where the ID we need is saved. Since there is only one record in this tempory table, and only one field, it will only select the ID number you need and drop it into '#recID'. '#recID' now has the ID number you want and you can use it how you want like i have used it below.
INSERT INTO staff(Staff_comp_id)
VALUES (#recID)
End
-- So there you go. I was looking for something like this for ages, with this detailed break down, I hope this helps.