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

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)

Related

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.

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

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));

Can you tell me when data was inserted into a table

I am using MS SQL Server 2008 and I have an sql table with some data that is inserted daily at 6 am by an sql job. The problem I have is that some data has been inserted separately into the job and I need to know when this data was added.
Is there a query I can run that will show me this?
I think the short answer is NO, there's no magic, ad hoc SQL query that will let you go back after the fact and find out when a row was inserted.
If you want to know when a row is inserted, the easiest thing would be to simply add a date or timestamp field with a default value (like getDate()) that automatically fills in the date/time when the row is inserted.
There are, of course, SQL logs available that will let you track when rows are inserted, updated, deleted, etc., but those require set up and maintenance.
Third option would be to have the program that's inserting the data perform some logging.
Add a date field to the table. You can give it a default value of GETDATE()
Then ORDER BY that field.
SELECT Column1, Column2, NewDateColumn
FROM YourTable
ORDER BY NewDateColumn
what i would do is :
/* add new column to keep inserted row date */
ALTER TABLE [schemaName].[tableName] ADD [RecTime] DATETIME;
/* update the existing rows with the current date since there is no way to guess their insertion date */
UPDATE [schemaName].[tableName] SET [RecTime] = GETDATE();
/* and set a constraint to the RecTime column to set current date on every new row added */
ALTER TABLE [schemaName].[tableName] ADD CONSTRAINT [DF_tableName_RecTime] DEFAULT (GETDATE()) FOR [RecTime]
then you can get those rows like :
SELECT *
FROM [schemaName].[tableName]
WHERE NOT(DATEPART(hh, RecTime) = 6 AND DATEPART(mi, RecTime) <= 20)
you can 'play' with '20' if you know how long sql job run
you probably need to look at SQL CREATE TRIGGER to add the logic to know when the data is being added and log that info in another table for further actions. Without further details I am not sure we can say more than that.
As you're referring to data which has already been inserted, the answer is No, unless you already have a datetime column which has a default value of GETDATE(). The best you can manage after the event has occurred is to look at the sequence of rows and determine that it was between two known times.

Sql Column had no values

I have a sql table that I am trying to add a column from another table to. Only when I execute the alter table query it does not pull the values out of the table to match the column where I am trying to make the connection.
For example I have column A from table 1 and column A from table 2, they are supposed to coincide. ColumnATable1 being an identification number and ColumnATable2 being the description.
I tried this but got an error...
alter table dbo.CommittedTbl
add V_VendorName nvarchar(200)
where v_venkey = v_vendorno
It tells me that I have incorrect syntax... Anyone know how to accomplish this?
alter table dbo.CommittedTbl
add V_VendorName nvarchar(200);
go
update c
set c.V_VendorName = a.V_VendorName
from CommittedTbl c
join TableA a
on c.v_venkey = a.v_vendorno;
go
I'm just guessing at your structure here.
alter table 2 add column A <some_type>;
update table2 set column A = (select column_A from table2 where v_venkey = v_vendorno);
Your names for tables and columns are a bit confusing but I think that should do it.
There is no WHERE clause for an ALTER TABLE statement. You will need to add the column (your first two lines), and then insert rows based upon a relationship you define between the two tables.
ALTER TABLE syntax:
http://msdn.microsoft.com/en-us/library/ms190273%28v=sql.90%29.aspx
There are several languages within SQL:
DDL: Data Definition Language - this defines the schema (the structure of tables, columns, data types) - adding a column to a table affects the table definitions and all rows will have that new column (not just some rows according to a criteria)
DML: Data Manipulation Language - this affects data within a table, and inserting, updating or other changes fall into this and you can update some data according to criteria (and this is where a WHERE clause would come in)
ALTER is a DDL statement, while INSERT and UPDATE are DML statements.
The two cannot really be mixed as you are doing.
You should ALTER your table to add the column, then INSERT or UPDATE the column to include appropriate data.
Is it possible that you want a JOIN query instead? If you want to join two tables or parts of two tables you should use JOIN.
have a look at this for a start if you need to know more LINK
hope that helps!

How to combine columns within a table (Access SQL)

There are three columns of date information (month, day, year) in a table and I would like to create a new column in the table and combine those 3 columns into a the new column so that I can have a single formatted date. How can I do this? I know how to query this but I am trying to figure out how to copy this information to the original table. Thanks in advance.
If I understood well, you need to alter your table and add a datetime column
You need to do something like this
UPDATE YourTable
SET DATECOLUMN = '#' & DAYCOLUMN & '/' & MONTHCOLUMN & '/' & YEARCOLUMN & '#'
It was the sintaxis in access if i remember it well.
Greetings.
There are a number of way of managing such a data scrubbing exercise e.g.
CREATE a new table including a new NOT NULL column and omitting the now-redundant columns, INSERT..SELECT into the new table only the data you require, DROP the old table (you'll end up with a different table name which may not be a bad thing).
ADD a new nullable column to the existing table (or NOT NULL if you have an appropriate DEFAULT), UPDATE the new column, alter the column to make it NOT NULL then DROP the now-redundant columns.