SQL Table Column that uses input from Another Column in Same Table - visual-studio-2010

I want to have a column in table which calculates the value depending on the other column in the same table.
For example,
I have "Validity" Table with Columns "DateManufactured", "DateExpires"
The Date Expires column must calculate value suppose adding 30 days for Datemanufactured.
How Can we do this in Visual Studio2010->DataSet Design-> DataTable Column-> Properties->Expression
See relevant Image here
What could be the possible expression for this in terms of SQL Server Expressions?
Please Suggest optimal Solution.
Thanks in advance.

I believe you are looking for DateAdd
SELECT DATEADD(day, 30, '15 Dec 1988')

select dateadd(day,30,getdate())
this will take the current date(getdate())
add 30 days to it.

I would suggest creating a stored procedure to insert your data into your table with parameters of the values that needs to be inserted. you can then do your calculation based on your date parameter. Example:
Create Procedure InsertValidity
(
#City varchar(20),
#Area varchar(20),
...
#DatePosted datetime,
...
#UserID
)
as
declare #DurationFrom datetime
set #DurationFrom = (select DATEADD(dd,30,#DatePosted)
insert into Validity (City, Area, ..., DatePosted, ... UserID)
values(#City, #Area, ..., #DatePosted,...#DurationFrom,...#UserID)
This should solve your problem. Just complete the script by replacing the ... with your other data then execute the stored procedure in your application.

Related

Oracle SQL Developer- How to force 00:00:00 hour when inserting a new DATE value

In my Oracle SQL Developer, i have a table with a column with DATE format. When i insert a new row into this table, and insert a new value in this column, it automatically suggestes me the current date with the current hour.
I would like that it automatically suggestes me current date, but with 00:00:00 hour . Is there some setting or parameter that i can set in my SQL Developer to have this result?
We can't able to insert 00:00:00 hours ... the hour value should be between 1 to 12...
we can use below query to insert 00:00:00 hours but the value will be changed to 12:00:00
INSERT INTO TABLE (DATE_COL) VALUES
( TO_DATE ('11/16/2017 00:00:00 ', 'MM/DD/YYYY HH24:MI:SS '));
It seems to me that your DATE column is set with a DEFAULT of SYSDATE. This means, for any INSERT operations which do not specify a value in your DATE column, the current date and time will populate for that row. However, if INSERT operations do specify a value in your DATE column, then the specified date value will supersede the DEFAULT of SYSDATE.
If an application is controlling INSERT operations on that table, then one solution is to ensure the application utilizes the TRUNC() function to obtain your desired results. For example:
INSERT INTO tbl_target
(
col_date,
col_value
)
VALUES
(
TRUNC(SYSDATE, 'DDD'),
5000
)
;
However, if there are multiple applications or interfaces where users could be inserting new rows into the table, (e.g. using Microsoft Access or users running INSERT statements via SQL Developer) and you can't force all of those interfaces to utilize the TRUNC() function on that column during insertion, then you need to look into other options.
If you can ensure via applications that INSERT operations will not actually reference the DATE, then you can simply ALTER the table so that the DATE column will have a DEFAULT of TRUNC(SYSDATE). A CHECK CONSTRAINT can be added for further integrity:
ALTER TABLE tbl_target
MODIFY
(
col_date DATE DEFAULT TRUNC(SYSDATE, 'DDD') NOT NULL
)
ADD
(
CONSTRAINT tbl_target_CHK_dt CHECK(col_date = TRUNC(col_date, 'DDD'))
)
;
However, if users still have the freedom to specify the DATE when inserting new rows, you will want to use a TRIGGER:
CREATE OR REPLACE TRIGGER tbl_target_biu_row
BEFORE INSERT OR UPDATE OF col_val
ON tbl_target
FOR EACH ROW
BEGIN
:NEW.col_date := TRUNC(SYSDATE, 'DDD');
END tbl_target_biu_row
;
This will take of needing to manage the application code of all external INSERT operations on the table. Keep in mind, the above trigger is also modifying the DATE column if a user updates the specified value column.

convert oracle table column name to MM/DD/YYYY

I would like convert the column name to date.
for example the column name is today, i want to convert it dynamically to today's date like MM/DD/YYYY .
as of now the column name is "Today" i want it to be current date
You can't configure a column to change its name automagically. To reflect the current day or whatever else.
But, you can change the column name by using an alias when doing a query. In order to make the things the more transparent as possible, you might want to create a view. Here is an example:
-- Some table with a column named "TODAY"
CREATE TABLE T AS (SELECT LEVEL today FROM DUAL CONNECT BY LEVEL < 5);
-- Use PL/SQL to create a view on the given table
-- with a dynamic column name
DECLARE
today varchar(10) := TO_CHAR(SYSDATE,'DD/MM/YYYY');
query varchar(200) := 'CREATE OR REPLACE VIEW V'
|| ' AS SELECT today "' || today || '"'
|| ' FROM T';
BEGIN
execute immediate query;
END;
Then, to query the "table" with the right column name, you will simply need to query V instead of T:
SELECT * FROM V;
12/12/2014
1
2
3
4
If you recreate your view daily, say by calling the above PL/SQL code from a job, you will see each day a view with the current date as the column name. But, as the underlying table is left unchanged, you will still be able to query it using the canonical name today. Which is important for example if you need to perform join on that table.
That being said, I'm not sure I will push toward such a solution. Use at your own risks!
If you want the column name heading to appear as something different than what the column name is defined in the table, you simply use the as "DisplayColumnName" clause for that column:
select user_name, today as "12/12/2014" from some_table;
But you would need to programatically generate the SQL statement for that to work. What coding environment you are using would dictate how to dynamically create a select statement.

Not getting desired output in Oracle

Table creation query:
create table students(
student_no number,
student_name varchar2(20),
student_addres varchar2(25),
student_dob date
joining_time date
)
Insert query:
insert into students
values (1,'ram','chittoor',to_date('02/04/2012','dd/mm/yyyy'),to_date('01:21:45','hh:mi:ss))
result:1 row inserted
Query to check insert:
select * from students
Result:
student_no student_name student_address student_dob joining_date
.......... ............ ............... ........... ............
1 ram chittoor 2-apr-2012 1-jul-2012
Qhy are the time values not getting inserted properly?
Your date is inserted properly, the tool you're using just seems to show the date without the time potion, check your tool settings;
Oracle has no support for Time only format, only date and time. Here is an excerpt from Oracle type documentation:
In a time-only entry, the date portion defaults to the first day of
the current month
Which is the case, you you get 1-July.
Based on this info, you'll need to rethink your queries.
Here is working example
If you want to get the Time from joining_time column then your,
Select query should be
SELECT student_no,
student_name,
student_addres,
student_dob,
TO_CHAR (joining_time, 'hh:mi:ss') AS joining_time
FROM students

Column name is masked in oracle indexes

I have a table in oracle db which has a unique index composed of two columns (id and valid_from). The column valid_from is of type timestamps with time zone.
When I query the SYS.USER_IND_COLUMNS to see which columns my table is using as unique index, I can not see the name of the valid_from column but instead I see smth like SYS_NC00027$.
Is there any possibility that I can display the name valid_from rather than SYS_NC00027$. ?
Apparently Oracle creates a function based index for timestamp with time zone columns.
The definition of them can be found in the view ALL_IND_EXPRESSIONS
Something like this should get you started:
select ic.index_name,
ic.column_name,
ie.column_expression
from all_ind_columns ic
left join all_ind_expressions ie
on ie.index_owner = ic.index_owner
and ie.index_name = ic.index_name
and ie.column_position = ic.column_position
where ic.table_name = 'FOO';
Unfortunately column_expression is a (deprecated) LONG column and cannot easily be used in a coalesce() or nvl() function.
Use the below to verify the col info.
select column_name,virtual_column,hidden_column,data_default from user_tab_cols where table_name='EMP';

SQL Server 2008 search for date

I need to search rows entered on a specific date.
However the datatype of column I need to search on is datetime, and the datatype of argument is Date.
I can use the the query like
Select result
from table
where
convert(date, Mycolumn) = #selectedDate
but this would affect the SARGability of the query and will not use indexes created on mycolumn.
I was trying to use the following query:
Select result
from table
where
Mycolumn
BETWEEN #selectedDate AND Dateadd(s, -1, Dateadd(D, 1, #selectedDate))
However this does not work since the #selectedDate is Date type and a second can't be added or removed.
Can someone help me with a working query?
Thanks.
It is my understanding that using:
convert(date, Mycolumn) = #selectedDate
is SARGable. It will use the index on Mycolumn (if one exists). This can easily be confirmed by using the execution plan.
Select result
from table
where
Mycolumn >= #selectedDate
AND Mycolumn < Dateadd(D, 1, #selectedDate)
If you need to do these searches a lot, you could add a computed, persisted column that does the conversion to DATE, put an index on it and then search on that column
ALTER TABLE dbo.YourTable
ADD DateOnly AS CAST(MyColumn AS DATE) PERSISTED
Since it's persisted, it's (re-)calculated only when the MyColumn value changes, e.g. it's not a "hidden" call to a stored function. Since it's persisted, it can also be indexed and used just like any other regular column:
CREATE NONCLUSTERED INDEX IX01_YourTable_DateOnly ON dbo.YourTable(DateOnly)
and then do:
SELECT result FROM dbo.YourTable WHERE DateOnly = #SelectedDate
Since that additional info is stored in the table, you'll be using a bit more storage - so you're doing the classic "space vs. speed" trade-off; you need a bit more space, but you get more speed out of it.

Resources