Create a time with time in SQL Server - sql

I am very new to this please any help would be great! I am creating a date warehouse for a credit card company for school and in this table it is asking for the table TRANSACTION to having the following Date, Time, Amount, and Authorization Code. Here is what I have so far for just this table
CREATE TABLE transactions (
trans_date DATE PRIMARY KEY NOT NULL,
trans_time DATETIME NOT NULL,
trans_amount DECIMAL NOT NULL,
auth_code VARCHAR(15) NOT NULL
);
INSERT INTO transactions VALUES ('1984-12-15', '2000-03-15 11:15:23', 200.00, 'IH1546');
INSERT INTO transactions VALUES ('2001-01-22', '2014-05-15 12:45:20', 300.00, 'IH2563');
INSERT INTO transactions VALUES ('1998-10-30', '2017-01-14 13:11:45', 400.00, 'IH4457');
INSERT INTO transactions VALUES ('2003-02-11', '2007-10-28 09:05:56', 500.00, 'IH8977');
INSERT INTO transactions VALUES ('1985-12-23', '2009-06-29 16:37:03', 600.00, 'IH9975');
SELECT *
FROM transactions;
The problem I am encountering is
Msg 273, Level 16, State 1, Line 18
Cannot insert an explicit value into a timestamp column. Use INSERT with a column list to exclude the timestamp column, or insert a DEFAULT into the timestamp column.
Can anyone help me or walk me through what I need to do for time, I have been searching online for two days and not really finding anything that comes close to what I need. Each record should all have different times in them?

Related

Insert current date time in a column of and keep it constant

i am using sql server in making my project with javafx. Their i have a table of purchase and sale. One of the column of both of them is date having current date and time to store them as a record that this transaction has been saved in this time.
Now i am using the that date column with varchar datatype and have using computed column specification with following function:
(CONVERT([varchar](25),getdate(),(120)))
but when i select records from that table using query
SELECT pr.Date, p.Name, pr.Quantity, s.Name, p.Pur_Price
FROM (([Product] AS p
INNER JOIN [Purchase] AS pr ON pr.Product_id=p.Product_id)
INNER JOIN [Supplier] AS s ON s.Supplier_Id=p.Supplier_Id)
WHERE pr.Date>= dateadd(dd, 0, datediff(dd, 0, getdate()-30))
but it selects all the records keeping all date records to current date and time. Thanks in advance.
Looking forward for your good replies.
The problem is that your Date column is computed on the fly and not actually stored in the table. So each time you SELECT from that table, the expression of the computed column is calculated (CONVERT([varchar](25),getdate(),(120))) thus resulting in the same value for all rows.
A fix would be using a PERSISTED computed column so that values are actually stored with the table when inserting or updating:
CREATE TABLE Product (
OtherColumns INT,
[Date] AS (CONVERT([varchar](25), getdate(), 120)) PERSISTED)
The problem with this is that non-deterministic expressions can't be persisted, as this error message pops up:
Msg 4936, Level 16, State 1, Line 1 Computed column 'Date' in table
'Product' cannot be persisted because the column is non-deterministic.
You have several other options for this. Please use DATE or DATETIME columns to store and handle dates and avoid using VARCHAR for this as it brings many problems. The following examples use DATETIME:
Use a DEFAULT constraint linked to the column with the expression you want:
CREATE TABLE Product (
OtherColumns INT,
[Date] DATETIME DEFAULT GETDATE())
INSERT INTO Product (
OtherColumns) -- Skip the Date column on the INSERT
VALUES
(1)
SELECT * FROM Product
OtherColumns Date
1 2018-12-14 08:49:08.347
INSERT INTO Product (
OtherColumns,
Date)
VALUES
(2,
DEFAULT) -- Or use the keyword DEFAULT to use the default value
SELECT * FROM Product
OtherColumns Date
1 2018-12-14 08:49:08.347
2 2018-12-14 08:50:10.070
Use a trigger to set the value. This will override any inserted or updated value that the original operation set (as it will execute after the operation, as stated in it's definition).
CREATE TRIGGER utrProductSetDate ON Product
AFTER INSERT, UPDATE
AS
BEGIN
SET NOCOUNT ON
UPDATE P SET
Date = GETDATE()
FROM
inserted AS I
INNER JOIN Product AS P ON I.OtherColumns = P.OtherColumns -- Assuming PK or Unique columns join
END
Thanks all of you. But i solved my problem by putting my date Column of that table into datetime data type and i my query i have entered the date using getdate() method. It worked for me to save current date and time in my purchase and sale table.

Sqlite3 trigger with UPSERT

I'm using sqlite3 on my Rails project and I need to create a trigger that automatically inserts into the table when another referencing table is updated.
For example, I have 2 tables Breakdown and Total, schemas for each table are as below.
Breakdown
Date TEXT NOT NULL,
Amount DECIMAL NOT NULL
Total
Date TEXT NOT NULL,
Daily_Total DECIMAL NOT NULL,
FOREIGN KEY (Date) REFERENCES Breakdown(Date)
Then, below is my trigger creation.
CREATE TRIGGER update_sum AFTER INSERT ON Breakdown
...> BEGIN
...> INSERT OR REPLACE INTO Total (Date, Daily_Total)
...> VALUES (Breakdown.Date,
...> (SELECT SUM(Amount) FROM Breakdown WHERE Date = Total.Date));
...> END;
So, my idea is when I insert into Breakdown table as **INSERT INTO Breakdown VALUES (Date('now'),19.99);** then Total table gets updated by either inserting or update.
However, when I insert into Breakdown table, I get an error saying Error: no such column: Breakdown.Date
Can anyone direct me to the point where I'm doing wrong, please?
Thank you!
You can access the values of the row that caused the trigger to trigger, but that 'table' is called NEW:
INSERT ... VALUES(NEW.Date, (SELECT SUM... WHERE Date = NEW.Date));

SQL - Poor design choice?

Please take a look at the SQL below:
create table DatasetToID(
Dataset varchar(100),
ID INT,
Name varchar(100),
age varchar(100),
primary key (dataset,id)
)
INSERT INTO DatasetToID VALUES ('Sales', 1, 'Ian Ratkin','30')
INSERT INTO DatasetToID VALUES ('Finance', 1, 'Bert Edwards','56')
INSERT INTO DatasetToID VALUES ('Production', 1, 'Marie Edwards','56')
INSERT INTO DatasetToID VALUES ('Sales', 2, 'Karen Bromley','30')
INSERT INTO DatasetToID VALUES ('Finance', 2, 'Steven Tardy','56')
INSERT INTO DatasetToID VALUES ('Production', 2, 'Eric Bishop','56')
create table Deletion(
Dataset varchar(100),
ID INT, decision bit,
date datetime
)
INSERT INTO Deletion VALUES ('Sales', 1, 1, '2013-01-01')
INSERT INTO Deletion VALUES ('Finance', 2, 1, '2013-01-01')
INSERT INTO Deletion VALUES ('Sales', 1, 0, '2013-02-02')
A live system I support is designed like this. Records are deleted from DatasetToID and Deletion at the end of each month if the most recent Deletion decision (bit) is true. In the case of the above Finance,2 will be deleted but Sales,1 will not because Sales,1 most recent decision is 0 (false).
I believe this is quite a poor design. I believe that Dataset and ID should be in a different table like i.e. not DatasetToID. The original developer seemed to disagree before he left. I am wandering if I am wrong.
It's a denormalized design, which is common in some scenarios for this kind of work. In particular, a periodic routine like a monthly delete or archive should really not be influencing your schema design. If this is the only overlap between that key pair, then I would say your old dev was probably right. If these two columns appear together in tables, however, you are probably right, there should be a master record for this pairing.

Sequence error in sql. Sequence number not allowed here

I am trying to run the following query to insert a number of nodes with an id that auto-increments as nodes are loaded into the table.
However I get the error, ORA-02287: sequence number not allowed here whenever I run it.
INSERT INTO V1144Engine.T_NODES VALUES
(
(SELECT V1144ENGINE.S_PK_NODES.NEXTVAL FROM dual),
1,
'Chemistry of Life',
0,1,
SYSDATE,
NULL,
'CON.3.1',
NULL
);
I have tried running
SELECT V1144ENGINE.S_PK_NODES.NEXTVAL from dual
This works fine and returns the number that I want.
How do I get around this? I am running on Oracle 11g.
Also it would be much appreciated if the query were still runnable on one line as I am making these in a spreadsheet and would like to still be able to do so.
There is no need to have the inner SELECT. Simply
INSERT INTO V1144Engine.T_NODES
VALUES(V1144ENGINE.S_PK_NODES.NEXTVAL,
1,
'Chemistry of Life',
0,
1,
SYSDATE,
null,
'CON.3.1',
null);
In general, though, you want to list the columns that you are providing values for in your INSERT statement. That not only documents the columns so that a future developer doesn't have to look up the order of columns in a table, it protects you if new columns are added to the table in the future.
INSERT INTO V1144Engine.T_NODES( <<list of columns>> )
VALUES(V1144ENGINE.S_PK_NODES.NEXTVAL,
1,
'Chemistry of Life',
0,
1,
SYSDATE,
null,
'CON.3.1',
null);

Informix 7.3 - Declaring a date column data type with default as current date on insert/update

Looking for your help again Jonathan Leffler!
I am creating a table on Informix 7.3 and need a timestamp field that will default to today on inserts and updates.
How can I define a date/datetime/timestamp column for a table with a default value of the current time?
Here is a field definition for a simple date field:
column upd_date date
comments ""
desc "Last update date"
heading "Last update date"
text "Last update date"
attributes
(
)
There is also some other syntax in schema files that have comments about what the default should be:
column beg_date date{DEF: date academic session/subsession officially begins}
comments ""
desc "Beginning date."
heading "Beg Date"
text "Date - Begin"
attributes
(
)
I'm not sure of any other tables that have this functionality, and I'm not even 100% sure that it is supported, but if there is a way, I'd love to know.
The only good lead I've found on the topic is here
Anyone have any ideas/solutions?
More findings:
http://www.4js.com/techdocs/genero/fgl/devel/DocRoot/User/DatabaseSchema.html
Cast Date in Informix
There is a datetime column type that I found in another table def:
column beg_time datetime year to minute
comments ""
desc "Beginning date and time of period"
heading "Beg Time"
text "Date/Time - Slot Begin"
attributes
(
)
{DEF: date and time this group/person may register}
I don't recognize the meta-language used in the question, so I'm not sure what that is capable of compared with what the DBMS is capable of.
CREATE TABLE ExampleDatesAndTimes
(
rownumber SERIAL NOT NULL PRIMARY KEY,
date_column DATE DEFAULT TODAY NOT NULL,
datetime_yd DATETIME YEAR TO DAY
DEFAULT CURRENT YEAR TO DAY NOT NULL,
datetime_ys DATETIME YEAR TO SECOND
DEFAULT CURRENT YEAR TO SECOND NOT NULL,
datetime_hs DATETIME HOUR TO SECOND
DEFAULT CURRENT HOUR TO SECOND NOT NULL,
payload VARCHAR(255) NOT NULL
);
This gives you a table in which each of the 4 temporal columns will be assigned a default value if you don't specify it in the INSERT operation:
INSERT INTO ExampleDatesAndTimes(Payload) VALUES ("Hello");
On the other hand, if you specify the columns, then the specified values take precedence. I'm assuming the DBDATE="Y4MD-" so that DATE values look like DATETIME YEAR TO DAY values:
INSERT INTO ExampleDatesAndTimes
VALUES(0, '1066-10-14', '2001-01-01', '2012-11-10 09:08:07',
'23:23:21', "Gezundheit");
Here, the values are all specified, so those are the values stored. Note that programs such as ISQL Perform (and most typical I4GL programs) will provide values for all the columns so the default mechanism won't take effect.
You can play with triggers to alter the values on UPDATE, so you can have a date inserted and a 'last updated' column (and whodunnit columns - created_by and updated_by - if you want). Again, you have to worry about defaults versus explicitly provided values.
Now, since you are using IDS 7.3x, which finally went out of service a year or two ago, you have slightly different functionality from what is available in IDS 11.70. You should be looking at upgrading.
I found this code (eventually) for playing with triggers on update. It dates from 2006.
CREATE TABLE talx_000
(
i SERIAL NOT NULL PRIMARY KEY,
s CHAR(30) NOT NULL,
m_user VARCHAR(32) DEFAULT USER NOT NULL,
m_time DATETIME YEAR TO SECOND DEFAULT CURRENT YEAR TO SECOND NOT NULL
);
CREATE PROCEDURE current_user_time()
RETURNING VARCHAR(32) AS m_user, DATETIME YEAR TO SECOND AS m_time;
RETURN user(), CURRENT YEAR TO SECOND - 1 UNITS DAY;
END PROCEDURE;
CREATE TRIGGER upd_talx_000 UPDATE ON talx_000
REFERENCING NEW AS NEW FOR EACH ROW
(EXECUTE PROCEDURE current_user_time() INTO m_user, m_time);
INSERT INTO talx_000(s) VALUES("cached nonsense");
INSERT INTO talx_000(s, m_user) VALUES("inserted user", "sphinx");
INSERT INTO talx_000(s, m_time)
VALUES("inserted time", DATETIME(1066-10-14 15:23:31) YEAR TO SECOND);
INSERT INTO talx_000(s, m_time, m_user)
VALUES("inserted both", DATETIME(1805-10-21 13:15:00) YEAR TO SECOND,
"nelson");
SELECT * FROM talx_000;
DROP TRIGGER upd_talx_000;
CREATE PROCEDURE upd_talx_000(i_val INTEGER);
UPDATE talx_000
SET m_user = "brandywine",
m_time = DATETIME(3019-03-25 13:00:00) YEAR TO SECOND
WHERE i = i_val;
END PROCEDURE;
CREATE TRIGGER upd_talx_000 UPDATE ON talx_000
REFERENCING NEW AS NEW FOR EACH ROW
(EXECUTE PROCEDURE upd_talx_000(NEW.i));
INSERT INTO talx_000(s) VALUES("cached nonsense");
INSERT INTO talx_000(s, m_user) VALUES("inserted user", "sphinx");
INSERT INTO talx_000(s, m_time)
VALUES("inserted time", DATETIME(1066-10-14 15:23:31) YEAR TO SECOND);
INSERT INTO talx_000(s, m_time, m_user)
VALUES("inserted both", DATETIME(1805-10-21 13:15:00) YEAR TO SECOND,
"nelson");
SELECT * FROM talx_000;
Have fun!
TABLE sample
(
timestamp DATETIME(YEAR TO SECONDS)
)
In Informix-SQL Perform screen:
INSTRUCTIONS
AFTER EDITADD OF sample.timestamp
LET screen_tag = CURRENT
AFTER EDITUPDATE OF sample.timestamp
LET screen_tag = CURRENT
NOTE: I never use WITHOUT NULL on a DATE or DATETIME column since it's better to have an absent value as opposed to 12/31/1899 when WITHOUT NULL is specified on a temporal column.
This is tested & works for me - ONLY FOR INSERTS. I assume that you can handle the update scenario with a trigger if you need the field to update to the current date on every update
column use_date date default today not null
comments ""
desc "Date this use case was executed"
heading "Usage date"
text "Usage date"
attributes
(
)