Calculate the age and Insert it to an already column via SQL Server - sql

I have a table in database which is already has the data, but now I added new column called Vol_Age and it has NULL value. I want that column filled by calculating Age, the data comes from Vol_Date_of_Birth column, I need a query that calculate the age and insert it to the Vol_Age column.
which we can use Insert or Update, and how we can do it?!
Please forgive me for my English.
Thanks

Keep in mind that since you added the column to the database, any values within that column will retain their value. As time goes on, you will need to keep updateding the values within the database.
Another approach would be to remove the column and make it a computed column instead. This way, the age is caculated at query time rather than from your last update.
ALTER TABLE tbname ADD Vol_Age AS DATEDIFF(YEAR, Vol_Date_Of_Birth, GETDATE())

Try using the DateDiff function:
SELECT DATEDIFF(year,GETDATE(),Vol_Age)

you can use this:
UPDATE Personal_Info SET vol_Age = (SELECT (DATEDIFF(YEAR, Vol_Date_Of_Birth,GETDATE()) + CONVERT(REAL,(DATEDIFF(month, Vol_Date_Of_Birth,GETDATE()) % 12))/12) AS AGE
FROM Personal_Info)

I got answers from different places and merged the answers to get this:
UPDATE Personal_Info SET vol_Age = (select convert(int,DATEDIFF(d, Vol_Date_of_Birth, getdate())/365.25));

Related

Can I add a column to a temporary table that stores part of a date (year) from another column?

I want to select all columns from a table into a #temp1 table based on criteria.
In addition, I want to add an additional column that is the year portion only of a captured date field. I want the original whole date and add a separate column of just the year part of each date.
I tried to alter the #temp1 table and add a column called EnteredYear.
I then tried an update with a set EnteredYear = DATEPART(year, EnteredDate), but I am getting a syntax error.
Searching learn.microsoft.com and StackOverflow, but I haven't hit upon the right syntax yet.
If I understand correctly, you can try to use the computed column which needs to ALTER TABLE because it is a schema change.
ALTER TABLE #Temp ADD EnteredYear AS DATEPART(year, EnteredDate)
sqlfiddle
Temp tables work almost like persisten tables. You manipulate them wit INSERT, UPDATE DELETE statements. So if you have already added your new column you could write:
UPDATE #temp1 set EnteredYear = DATEPART(year, EnteredDate)

Add timestamp to existing table

I have a SQL Server table with just 3 columns, one of which is of type varbinary. The data in this column is actually a Json document which among other properties contains information about when the data was last modified. Unfortunately the SQL table itself does not contain information about when its rows were modified.
Now when doing sorting and filtering of the data I of course don't want fetch all rows in order to find e.g. the latest 100 entries.
So my question is: does SQL Server somehow remember when a row was added/modified? I have tried adding a timestamp and this is applied to all existing rows but this is applied randomly I think, because the sorting doesn't work. I don't need a datetime or anything, I just want to be able sort the records based on when they were last modified.
Thanks
For those looking to insert a tamestamp column of type DateTime into an existing DB table, you can do this like so:
ALTER TABLE TestTable
ADD DateInserted DATETIME NOT NULL DEFAULT (GETDATE());
The existing records will automatically get the value equal to the date/time of the moment when column is added.
New records will get up-to-date value upon insertion.
SQL Server will not track historically when a row was inserted or modified so you need to rely on the JSON data to figure that out yourself. You are going to need a new column to make this efficient to query. Once you have your new column you have some options:
Loop through all your records populating the new column with the relevant value from the JSON data.
If your version of SQL Server is recent enough, you can query the JSON data directly. Populate this column using a query like this:
UPDATE MyTable
SET MyNewColumn = JSON_VALUE(JsonDataColumn, '$.Customer.DateCreated')
The downside of this method is that you need to maintain this
Make SQL Server compute the value from the JSON automatically, for example:
ALTER TABLE MyTable
ADD MyNewColumn AS JSON_VALUE(JsonDataColumn, '$.Customer.DateCreated')
And, create an index to make it efficient:
CREATE INDEX IX_MyTable_MyNewColumn
ON MyTable(MyNewColumn)
Use a new column CreatedDate and store datetime every time you make an Insert.
You could use GetDate() for inserting date in the column.
A UpdatedDate column can be used for updates.
in order to find e.g. the latest 100 entries.
Timestamp is indeed what you need.
It's ever-increasing value, it's updated automatically, so you are always able to find all last modified/inserted rows.
Here is an example:
create table dbo.test1 (id int);
insert into dbo.test1 values(1), (2), (3);
alter table dbo.test1 add ts timestamp;
update dbo.test1
set id = 10
where id = 2
select top 1 *
from dbo.test1
order by ts desc;
--id ts
--10 0x000000001FCFABD2
insert into dbo.test1 (id)
values (100);
select top 1 *
from dbo.test1
order by ts desc;
--id ts
--100 0x000000001FCFABD3
As you see, you always get the last modified/inserted row.
For your purpose just use
select top 100 *
...
order by ts desc;
Thanks. Apparently I didn't look hard enough before I posted this question. The question has been asked a couple of times before and the answer is: Nope! There is no easy solution to this.
SQL Server does not keep track of when a record was created or modified, which was somehow what I was looking for. So I will go for the next best solution, which is probably to create a datetime column, retrieve the modified date from the Json document and then update the record. Or rather, the 1,4 million records:-(

every day Update the age depends on DOB automatically on each row in sql

I want to update the age of employees present in the database according to Date of birth (Field name is DOB),but it should update automatically after application start.
It seems like you want this field to be a part of your table, rather than in a view, as suggested by #jarlh in the comments. So why not change it into a computed column instead?
ALTER TABLE [YourTableName]
DROP COLUMN [Age];
ALTER TABLE [YourTableName]
ADD [Age] AS ([Your Age Formula]);
Use trigger to update the age field and make it run on the midnight of the day

SQL Server - Select list and update a field in each row

I hate to ask something that I know has been answered, but after 45 minutes of searching I yield to everyone here.
I have a table where I need to select a list of items based on a value, and then take one field and add a year to it and update another column with that value.
Example:
select * from table where description='value_i_need'
UPDATE table SET endDate=DATEADD(year, 1, beginDate) -- For each item in the select
EDIT: The select statement will return a ton of results. I need to update each row uniquely.
I don't know how to combine the select or loop through the results.
My SQL knowledge is limited, and I wish I could have figured this out without having to ask. I appreciate any help
Edit 2:
I have one table that I need to go through and update the end date on each item that matches a description. So I have 1000 "Computers" for example, that I need to update a field in each row with that description based on another field in the same row. All coming from one table
Try like this
UPDATE
Table T1
SET
T1.endDate=DATEADD(year, 1, beginDate)
WHERE T1.description='value_i_need'
Unless I missed something, you should be able to simply add your criteria to your update statement as follows:
UPDATE [table]
SET endDate=DATEADD(year, 1, beginDate)
WHERE description='value_i_need'
UPDATE T
SET T.END_DATE = DATEADD(YEAR,1,T.BEGINDATE)
FROM TABLE T
WHERE T.DESCRIPTION = 'value_i_need
Do you mean:
UPDATE [TABLE] SET ENDDATE=DATEADD(YEAR,1,BEGINDATE) WHERE DESCRIPTION='VALUE_I_NEED'

SQL SELECT or INSERT INTO query

I'm working with SQL Server 2000. I need to take the results from one column (VALIMIT) and insert them into another column (VALIMIT2012) in the same table (lending_limits).
My question is do I need to do a SELECT query first, or do I just start with an INSERT INTO query and what the proper syntax would be for the INSERT INTO query.
You can do this with an UPDATE statement:
update lending_limits
set VALIMIT2012 = VALIMIT
Neither. You don't insert columns, you insert rows, so what you want is an update:
update SomeTable
set VALIMIT2012 = VALIMIT
Note: It looks like you have one column per year, which is bad database design. If you have different data for each year, you should put that in a separate table, so that you get the year as data, not part of the column name.
UPDATE TableName SET VALIMIT2012 = VALIMIT