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

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.

Related

SQL Server - Looking for a way to shorten code

I'm basically very new to SQL Server, so please bare with me. Here is my problem:
I have a table with (let's say) 10 columns and 80k rows. I have 1 column called Date in the format of YYYY-MM-DD type varchar(50) (can't convert it to date or datetime type I tried, the initial source of data is not good).
**Example :
Table [dbo].[TestDates]
Code
SellDate
XS4158
2019-11-26
DE7845
2020-02-06
What I need to do is to turn the YYYY-MM-DD format to DD/MM/YYYY format. After a lot of tries (I tried the functions (DATE_FORMAT, CONVERT, TO_DATE etc) and this is solution :
1- I added a primary key for join purpose later (ID)
2- I split my date column in 3 columns in a whole new table
3- I merged the 3 columns in the order I need with the delimiter of my choice (/) in the same new table
4- I copied the good column to my initial table using the primary key ID I created before
alter table [dbo].[TestDates]
add ID int not null IDENTITY primary key;
SELECT ID,
FORMAT(DATEPART(month, [SellDate]),'00') AS Month,
FORMAT(DATEPART(day, [SellDate]),'00') AS Day,
FORMAT(DATEPART(year, [SellDate]),'0000') AS Year
INTO [dbo].[TestDates_SPLIT]
FROM [dbo].[TestDates]
GO
ALTER TABLE [dbo].[TestDates_SPLIT]
ADD SellDate_OK varchar(50)
UPDATE [dbo].[TestDates_SPLIT]
SET SellDate_OK = [Day] + '/' + [Month] + '/' + [Year]
ALTER TABLE [dbo].[TestDates_SPLIT]
DROP COLUMN Month, Day, Year
ALTER TABLE [dbo].[TestDates]
ADD SellDate_GOOD varchar(50)
UPDATE [dbo].[TestDates]
SET [TestDates].SellDate_GOOD = [TestDates_SPLIT].SellDate_OK
FROM [dbo].[TestDates]
INNER JOIN [dbo].[TestDates_SPLIT]
ON [TestDates].ID = [TestDates_SPLIT].ID
This code works but i find too heavy and long, considering I have 6 more dates columns to work on. Is there a way to make it shorter or more efficient? Maybe with SET SellDate = SELECT (some query of sorts that doesn't require to create and delete table)
Thank you for your help
I tried the usual SQL functions but since my column is a varchar type, the converting was impossible
You should not be storing dates as text. But, that being said, we can try doing a rountrip conversion from text YYYY-MM-DD to date to text DD/MM/YYYY:
WITH cte AS (
SELECT '2022-11-08' AS dt
)
SELECT dt, -- 2022-11-08
CONVERT(varchar(10), CONVERT(datetime, dt, 121), 103) -- 08/11/2022
FROM cte;
Demo

Display Now date and Time in SQl table column

I want to be able to have todays date and time now in a table column
If my table is say Table1, basically it should display the time and date when
SELECT * FROM Table1 is run.
I've tried the following but they just show the time from the moment in time I assign the value to column
ALTER TABLE Table1
ADD TodaysDate DateTime NOT NULL DEFAULT GETDATE()
and
ALTER TABLE Table1
ADD TodaysDate DateTime
UPDATE Table1
SET TodaysDate = GETDATE()
Hope this is clear. any help is appreciated.
Thanks
In SQL Server you can use a computed column:
alter table table1 add TodaysDate as (cast(getdate() as date));
(use just getdate() for the date and time)
This adds a "virtual" column that gets calculated every time it is referenced. The use of such a thing is unclear. Well, I could imagine that if you are exporting the data to a file or another application, then it could have some use for this to be built-in.
I hope this clarifies your requirement.
The SQL Server columns with default values stores the values inside the table. When you select the values from table, the stored date time will be displayed.
There are 2 options I see without adding the column to the table itself.
You can use SELECT *, GETDATE() as TodaysDate FROM Table1
You can create a view on top of Table 1 with additional column like
CREATE VIEW vw_Table1
AS
SELECT *, GETDATE() as TodaysDate FROM dbo.Table1
then you can query the view like you mentioned (without column list)
SELECT * FROM vw_Table1
This will give you the date and time from the moment of the execution of the query.

Order by on Two Datetime Fields .If one field is Null How to avoid Sybase from populating it with default datetime

I am using a Select Query to insert data into a Temp Table .In the Select Query I am doing order by on two columns something like this
insert into #temp
Select accnt_no,acct_name, start_date,end_date From table
Order by start_date DESC,end_date DESC
Select * from #temp
Here when there is an entry present in start_date field and an Null entry in the end_date field .During the order by operation Sybase is filling it with an Default date ( jan 1 1900 ) . I dont want that to happen .If the end_date field is Null . The data should be written just as Null .Any suggestion on how to keep it as Null even while fetching the data from the table .
The 1/1/1900 usually comes from trying to cast an empty string into a datetime.
Is your 'date' source column an actual datetime datatype or a string-ish varchar or char?
Sounds like the table definition requires that end_date not be null, and has default values inserted automatically to prevent them. Are you sure there are even nulls when you do a straight select on the table without the confusion of ordering and inserting?
I created a temp table with a nullable datetime column that has a default value.
Defaults are not there to handle nulls per se, they are there to handle missing values on inserts that were not supplied. If I run an insert without a column list (just as you have done) the default value does not apply and a null is still inserted.
I suggest adding the column list to your insert statement. This might prevent the problem (or expose a different problem in having them in the wrong order.)
insert into #temp (accnt_no, accnt_name, start_date, end_date)
select accnt_no,acct_name, start_date,end_date from ...
Here's a query that should help you find the actual defaults on any of the columns if you don't have access to the create script:
select c.name, object_name(cdefault), text
from tempdb..syscolumns c, tempdb..syscomments cm
where c.id = object_id('tempdb..#temp') and cm.id = c.cdefault

Insert a record into 2 tables in SQL Server using comma separated value

I have 2 table A and table B; table B is linked to table A through a foreign key.
TABLE A has a structure somewhat like this
PK Id
DeliveryChannelValue
DeliverychannelId
Date time
Table B has this structure
PK Id UniqueIdentifiers
Date time
FK tableA id
Now in a stored procedure, I get unique identifiers as comma separated value, so based on the number of items in that list, I have to create the same number of rows in table A and in table B.
If the number of items in comma separated value is 3, then there will be 3 rows to be inserted into table A and 3 rows into table B. I am trying to avoid a cursor.
Please suggest efficient way to do this.
You can use this CodeProject project split function to separate the values, and then use a known DateTime stamp to keep the tables in sync. This assumes these values aren't constantly updating which could cause a DateTime duplication issue: if that's the case, you'll need to use a add a GUID value in place of the YOURDATE field, below:
DECLARE #DATESTAMP DATETIME = GETDATE()
INSERT INTO TABLE_A (ID, YOURDATE)
SELECT item, #DATESTAMP
FROM dbo.[FN_SPLIT](#yourinputstring)
GO
INSERT INTO TABLE_B(YOURDATE, TABLE_A_ID)
SELECT #DATESTAMP, ID
FROM TABLE_A
WHERE YOURDATE = #DATESTAMP
GO

How do you choose specific id and time in SQL Server

I have this small program in C# that is constantly sending data to one of my tables (DataTable). The data format is always the same as well as the length.
There are 4 different IDs I am working with here: 2000,2001,2002, ...which are all in a different table. The ID column is the foreign key in my DataTable column.
Initially I thought I could just retrieve the last inserted row in my DataTable for a specific ID. However, I realized that the insert statement does allocate the values into the database in the order they are sent. Therefore, I decided to simply take an ID and get the last row of data based on the timestamp.
I have tried using DatePart but this limits me to only hours. I would want to display a time based on hours and min. ex: 2002 between '4:30:00' and '5:30:00'.
Also, would I have to do a join statement since I would be calling the ID column from another table?
Ive tried this so far: `
use LogDatabase
select * from dbo.DataTable
join CustomerTable
on(Customer_ID = CustIDFk)
where DATEPART(HH, TimeStamp)between 4 and 5 `
The incoming data string looks alot like this:
3-13-2011 3:30:21 2002: 45 Temp:81 Albany NY etc....
I have made columns for the every field of data in my DataTable. As you can see
2002 is the ID which is called Customer_ID in my CustomerTable. I have set this
as my primary key in the CustomerTable and CustIDFk is the foreign key to be linked
with Customer_ID. As you can see, I'm trying to join my Customer table with my Data
table in order to specify the ID. The DATEPART statement allows to give a time range
by either hour or min among others but does not allow a "between 4:30 and 5:30.
Would something like this work?
DECLARE #today DATETIME = CAST(FLOOR(CAST(GETDATE() AS FLOAT)) AS DATETIME)
SELECT *
FROM dbo.DataTable
WHERE TIMESTAMP BETWEEN DATEADD(mi, 30, DATEADD(hh, 4, #today)) AND DATEADD(hh, 5, #today)