SQL function in Hibernate insert statement - sql-server

How do include a function like getdate() in an insert statement for Hibernate query?
Lets say one of the properties of a mapped class is a datetime column how do put specify getdate() in order for the .save() method call to use the server timestamp?

Simple answer is don't include it in the insert statement and let SQL do it.
In the SQL table designer where you have the date column you are inserting into, set the Default Value to GETDATE() in the column properties and SQL Server will handle it for you.
Reference and sample: SQL Server GETDATE() Function
Table create script will look like this:
CREATE TABLE Orders
(
OrderId int NOT NULL PRIMARY KEY,
ProductName varchar(50) NOT NULL,
OrderDate datetime NOT NULL DEFAULT GETDATE()
)

Related

Alter data type of columns presents in manies tables with sql server script code

I'm tring to simplify my task. I'm want to use one script to change data type of all columns name like xxx_ID or Datexxx present in any table.
Example of column: Employee_ID, Customer_ID, Periode_ID, Contry_ID, DateInsert, DateUpdate,...
eg: ALTER all TABLE like dbo.tbl_* and all COLUMN like *_ID
///something like this
ALTER TABLE dbo.tbl_*
ALTER COLUMN *_ID varchar(15) NOT NULL
ALTER TABLE dbo.tbl_*
ALTER COLUMN Date* date NOT NULL
////SQL SERVER 2019
Can someone have idea?

Insert data from 1 table to another table in my local sql

Hi I need to run this script to insert data from another server to my local sql server. How I can identify the path?
CMMS is the name of the table that is in my local sql. My pc name is itfg234. what should I replace for CMMS in this query.
SELECT * INTO CMMS
FROM (
SELECT N'178670' AS [_IdxIdentity], N'E94E6A98-B71A-41ED-8B4B-F6472BA72ECD' AS [Contract_Other_DateBooked] ) t;
GO
CREATE TABLE customer(
customer_id VARCHAR(10) NOT NULL PRIMARY KEY,
customer_name VARCHAR(20) NOT NULL,
address VARCHAR(40) NOT NULL
);
CREATE TABLE employee(
emp_id VARCHAR(10) NOT NULL PRIMARY KEY,
emp_name VARCHAR(30) NOT NULL,
contact_no VARCHAR(10) NOT NULL
);
I need insert data from customer to employees
INSERT customer SELECT customer_id, customer_name, address FROM employee;
If the destination table already exists then you can't use SELECT * INTO or you'll get error
There is already an object named 'CMMS' in the database.
SELECT INTO creates the destination table. Use INSERT INTO dbo.CMMS ([column names]) instead.
The query is cut off so I can't see the entire subquery but I'll just mention you should give it an alias or you may get
Incorrect syntax near ')'.
If you are planning to run the command on the source server I recommend that you design it to run on the destination server and select from source using a linked server or OPENROWSET function. It's easier to pull data than push it.
Hope this helps.
try this
CREATE TABLE new_table_name LIKE old_table_name;
INSERT new_table_name SELECT * FROM old_table_name;
hope this one help you.

SQL GETDATE() in insert operations using Linq To Sql

Say i have the following table:
create table T (
ID int not null primary key,
Name varchar(10) not null,
CreatedAt datetime not null default GETDATE(),
UpdatedAt datetime not null default GETDATE()
)
and want to use with Linq 2 Sql. It perfectly generates type safe class with both CreatedAt and UpdatedAt properties non-nullable. Now i want to insert a new entry and want them both to be populated by a value from Sql Server, not with DateTime.Now which may differ. Is there a way to somehow send null to Sql Server without making the properties nullable? Also, i don't want to follow this solution as it requires additional network trip. It's very easy with good old SQL - just omit CreatedAt/UpdatedAt columns in the insert statement and you're fine but what are my options with Linq 2 Sql?
Can you check this link. there is a attribute called IsDbGenerated which can be annotated with your LINQ partial classes.
http://msdn.microsoft.com/en-us/library/system.data.linq.mapping.columnattribute.isdbgenerated.aspx#Y456

Automatic Adding Current DateTime In TableField

I am using SQL SERVER 2005 and i am also newbie to SQL SERVER
now i need to know that is there any way or any technique in SQL SERVER 2005
such that as soon as i add new record in table then current date-time should be added in to any given field of table.
Example:
Suppose i have CUSTOMER table
and it has fields say CustomerID,CustomerName,....,DateTime.
now whenever new customer added in this table then current date-time should be automatically added in to DateTime Field of CUSTOMER table.
In SSMS one can set the Default value or binding property of the appropriate column of the table property to getdate().
You need to add default constraint:
alter table MyTable add constraint MyColumnDefault default getdate() for MyColumn;
I'm not much of an expert in SQL but you could use TIMESTAMP for this, see:
http://msdn.microsoft.com/en-us/library/ms182776%28v=sql.90%29.aspx
It sounds like you should have a look at the timestamp data type:
http://msdn.microsoft.com/en-us/library/ms182776%28v=sql.90%29.aspx
Check table definition with default value
Declare #Table Table
(
Id int identity,[Name] varchar(100),CreatedDate DateTime default (Getdate())
)
insert into #Table([Name])
values ('yogesh')
insert into #Table ([Name])
values ('Bhadauriya')
insert into #Table ([Name])
values ('Yogesh Bhadauriya')
select *
From #Table

Add default value of datetime field in SQL Server to a timestamp

I've got a table that collects forms submitted from our website, but for some reason, when they created the table, they didn't put a timestamp in the table. I want it to enter the exact date and time that the record was entered.
I know it's in there somewhere, but I can't seem to find how to set the default value (like in Access, you use getNow() or Now()) but I don't know where to put it.
For modifying an existing column in an existing table:
ALTER TABLE YourTable ADD CONSTRAINT DF_YourTable DEFAULT GETDATE() FOR YourColumn
This can also be done through the SSMS GUI.
Put your table in design view (Right click on table in object explorer->Design)
Add a column to the table (or click on the column you want to update if it already exists)
In Column Properties, enter (getdate()) in Default Value or
Binding field as pictured below
In that table in SQL Server, specify the default value of that column to be CURRENT_TIMESTAMP.
The datatype of that column may be datetime or datetime2.
e.g.
Create Table Student
(
Name varchar(50),
DateOfAddmission datetime default CURRENT_TIMESTAMP
);
While the marked answer is correct with:
ALTER TABLE YourTable ADD CONSTRAINT DF_YourTable DEFAULT GETDATE() FOR YourColumn
You should always be aware of timezones when adding default datetime values in to a column.
Say for example, this datetime value is designed to indicate when a member joined a website and you want it to be displayed back to the user, GETDATE() will give you the server time so could show discrepancies if the user is in a different locale to the server.
If you expect to deal with international users, it is better in some cases to use GETUTCDATE(), which:
Returns the current database system timestamp as a datetime value. The database time zone offset is not included. This value represents the current UTC time (Coordinated Universal Time). This value is derived from the operating system of the computer on which the instance of SQL Server is running.
ALTER TABLE YourTable ADD CONSTRAINT DF_YourTable DEFAULT GETUTCDATE() FOR YourColumn
When retrieving the values, the front end application/website should transform this value from UTC time to the locale/culture of the user requesting it.
Disallow Nulls on the column and set a default on the column of getdate()
/*Deal with any existing NULLs*/
UPDATE YourTable SET created_date=GETDATE() /*Or some sentinel value
'19000101' maybe?*/
WHERE created_date IS NULL
/*Disallow NULLs*/
ALTER TABLE YourTable ALTER COLUMN created_date DATE NOT NULL
/*Add default constraint*/
ALTER TABLE YourTable ADD CONSTRAINT
DF_YourTable_created_date DEFAULT GETDATE() FOR created_date
The syntax for this when creating a new table is:
CREATE TABLE MyTable
(
MYTableID INT IDENTITY(1,1),
CreateDate DATETIME NOT NULL CONSTRAINT DF_MyTable_CreateDate_GETDATE DEFAULT GETDATE()
)
This works for me...
ALTER TABLE [accounts]
ADD [user_registered] DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ;
This also works:
CREATE TABLE Example(
...
created datetime default GETDATE()
);
Or:
ALTER TABLE EXAMPLE ADD created datetime default GETDATE();
This worked for me. I am using SQL Developer with Oracle DB:
ALTER TABLE YOUR_TABLE
ADD Date_Created TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL;
Let's say you create a database table for a registration system.
IF OBJECT_ID('dbo.registration_demo', 'U') IS NOT NULL
DROP TABLE dbo.registration_demo;
CREATE TABLE dbo.registration_demo (
id INT IDENTITY PRIMARY KEY,
name NVARCHAR(8)
);
Now a couple people register.
INSERT INTO dbo.registration_demo (name) VALUES
('John'),('Jane'),('Jeff');
Then you realize you need a timestamp for when they registered.
If this app is limited to a geographically localized region, then you can use the local server time with GETDATE(). Otherwise you should heed Tanner's consideration for the global audience with GETUTCDATE() for the default value.
Add the column with a default value in one statement like this answer.
ALTER TABLE dbo.registration_demo
ADD time_registered DATETIME DEFAULT GETUTCDATE();
Let's get another registrant and see what the data looks like.
INSERT INTO dbo.registration_demo (name) VALUES
('Julia');
SELECT * FROM dbo.registration_demo;
id name time_registered
1 John NULL
2 Jane NULL
3 Jeff NULL
4 Julia 2016-06-21 14:32:57.767
To make it simpler to follow, I will summarize the above answers:
Let`s say the table is called Customer
it has 4 columns/less or more...
you want to add a new column to the table where every time when there is insert... then that column keeps a record of the time the event happened.
Solution:
add a new column, let`s say timepurchase is the new column, to the table with data type datetime.
Then run the following alter:
ALTER TABLE Customer ADD CONSTRAINT DF_Customer DEFAULT GETDATE() FOR timePurchase
In SQLPlus while creating a table it is be like as
SQL> create table Test
( Test_ID number not null,
Test_Date date default sysdate not null );
SQL> insert into Test(id) values (1);
Test_ID Test_Date
1 08-MAR-19

Resources