SQL Server : fire trigger on SELECT? (Calculated Column) - sql-server

I need a column to be dynamic as such that a column DaysToExpiration is calculated based on the number of days between now and a date column Expiration Date.
My plan was to add a trigger that fires on a SELECTstatement of the table.
Is this possible? How?
Is there a better way to go about this?

You say "My plan was to add a Trigger that Fires on a SELECT statement of the table."
In that case why have a column at all, why not just select it in your final query?
Select DateDiff(day,getdate(),ExpirationDate) AS [DaysToExpiration]
If it must be persisted and stored in a column then you can make it a computed column as suggested in the comments. Or you could have the table trigger on UPDATE/INSERT so when the ExpirationDate is inserted or updated it sets the DaysToExpiration column to the result of the provided code.

No there is no provision of having trigger on SELECT operation. You can use stored procedure which takes parameters that are fetched from SELECT query and call this procedure after desired SELECT query.

Related

Can I use Stored procedure instead trigger in following case?

I've table with columns
studentId,
studentName,
markOne,
markTwo,
total.
I created a trigger to calculate total by adding markOne and markTwo..
whenever I update any one of the mark it automatically updates the total field.
ASK:
But this process can be achieved using Stored Procedure also then why we go for trigger instead Stored Procedure ?
Why would you use either a stored procedure or trigger? The best solution is to use a computed column:
alter table t add total as (markOne + markTwo);
This will calculate the value correctly whenever you refer to total.
Note: You'll need to remove the table from the table or re-create the table without the actual column.
In your condition, you don't require a trigger.You want to only update total field, so don't use triggers.
Trigger use in such a condition, when you add data for markone, marktwo, then it affects many tables.In more than 2-3 table, you need to update the database on two fields.Then you can use triggers.In your case you can simply use stored procedures.
Thanks .
You can create a view for this, so you dont have to alter your table.
create view vwMyTable as
select studentId,
studentName,
markOne,
markTwo,
(markOne + markTwo) as Total
from myTable
Then you can simply do
select * from vwMyTable

what can i do to update a column multiple times in same update query?

I want to update a column multiple times in same update query. I have a table in ms SQL database I want to update a field than again update that field in the same update query. for example i have a column "col" in sample table what i want to do is to set "col" values to "x" than to "y" in same SQL statement.
what i can do to achieve this?
You CANNOT do it in one command.
ONE Statement updates ONE Row, as many fields/values as you give.
You CAN update in one statement as long as you add two commands:
UPDATE table SET value=1;UPDATE table SET value=2;
But i think, that is not what you want?

Create column to constantly update with rownum in SQL Server

I have a table in SQL Server database. It has a column testrownum. I want to update the testrownum column to be rownum whenever row is created in the table automatically.
Is there any setting that I can turn on to achieve this?
Perhaps it is best to get a row number at the time you SELECT your data, by using the ROW_NUMBER() function.
As others have pointed out (comments section) the data in a table is essentially unordered. You can however assign a row number for a certain ordering when you select data as follows (suppose a table that only has one column being name):
SELECT
name,
rownr=ROW_NUMBER() OVER(ORDER BY name)
FROM
name_table
You can create trigger function.
Trigger is a function which is called every time data is insert, update or delete from table (you can specify when you want your function to be called when creating trigger). So you can add two triggers, one for insert and one for delete and just increment/decrement value you want.

How to retrieve the updated column values in sql server

I have "Order" table with more than 5,000 records. When I ran the update query unfortunately I forgot to give the ‘where’ condition.
Now the Date column in all the records has been updated. Is it possible to retrieve my existing column values.
Example:
Update Order
set ordered = getdate()
where Cusid=50
(here I forget to mention the where condition).
I am afraid NO, cause the update has already been committed. Unless you have a backup of the table it's no more can be undone.

Inserting the values with condition

Using SQL Server 2005
When i insert the date it should compare the date in the table.
If it is equal with other date, it should display a error message and also it should allow only to insert the next date.
For Example
Table1
Date
20091201
20091202
Insert into table1 values('20091202')
The above query should not allow to insert the same value
Insert into table1 values('20091204')
The above query also should not allow to insert the long gap date.
The query should allow only the next date.
It should not allow same date and long gap date.
How to insert a query with this condition.
Is Possible in SQL or VB.Net
Need SQL Query or VB.Net code Help
You could use a where clause to ensure that the previous day is present in the table, and the current day is not:
insert into table1 ([dateColumn])
select '20091204'
where exists (
select * from table1 where [dateColumn] = dateadd(d,-1,'20091204')
)
and not exists (
select * from table1 where [dateColumn] = '20091204'
)
if ##rowcount <> 1
raiserror ('Oops', 16, 1)
If the insert succeeds, ##rowcount will be set to 1. Otherwise, an error is returned to VB using raiserror.
Why not just have a table of dates set up in advance, and update a row once you want to "insert" that date?
I'm not sure I understand the point of inserting a new date only once, and never allowing a gap. Could you describe your business problem in a little more detail?
Of course you could use an IDENTITY column, and then have a computed column or a view that calculates the date from the number of days since (some date). But IDENTITY columns do not guarantee contiguity, nor do they even guarantee uniqueness on their own (unless you set up suc a constraint separately).
Preventing duplicates should be done at the table level with a unique constraint, not with a query. You can check for duplicates first so that you can handle errors in your own way (rather than let the engine raise an exception for you), but that shouldn't be your only check.
Sounds like your date field should just be unique with auto-increment.

Resources