I have a view with a field for date as a varchar. I need to change it to date time using the following code
CONVERT(DATETIME, MyDates)
This works fine when executing the view but I want to make the change permanent. I need some help with the syntax. So far I have
ALTER VIEW tableName
CONVERT(DATETIME, MyDates)
but it's obviously not working
Since a view (unless it's a materialized/indexed view which has some extra peculiarities) is more or less just a stored select query, what you do is to just change the select query and alter the view using that.
For example, if you have the view;
CREATE VIEW testview AS
SELECT id, value FROM test;
...where value is a varchar and you want it to be reflected in the view as a datetime, you can just issue;
ALTER VIEW testview AS
SELECT id, CAST(value AS DATETIME) value FROM test;
...to make it appear as a datetime in the view.
An SQLfiddle with a simple demo.
A view only fetches the data from the table as per the query.So you cannot change the datatype of the view. you have to change it in table.
Related
This is my view
CREATE VIEW seat_availability AS
SELECT flightid,flightdate, maxcapacity,
FROM flight
And I want to add 2 new columns named 'bookedseats' and 'availableseats' which don't exist in any tables but are columns I need to add.
I've done my research online and some say you can alter views by using:
ALTER VIEW
And some have said that you can't do that and have to edit from the view you've just created.
I've tried this:
CREATE VIEW seat_availability AS
SELECT flightid,flightdate, maxcapacity, bookedseats varchar(10), availableseats varchar(10)
FROM flight
which gave this error:
ERROR: syntax error at or near "varchar" LINE 2: ...ECT
flightid,flightdate, maxcapacity, bookedseats varchar(10...
I've also tried ALTER VIEW:
ALTER VIEW seat_availability AS
SELECT flightid,flightdate, maxcapacity, bookedseats varchar(10), availableseats varchar(10)
FROM flight
And I got this error:
ERROR: syntax error at or near "AS" LINE 1: ALTER VIEW
seat_availability AS
It would be easy to add columns if they existed in other tables but because I need to add 2 columns that don't exist in any table, it's proving difficult to do. If someone could help it would be very appreciated. Thank you.
Perhaps I may need to drop the view? and start again with two new columns added but how do I add them since they don't exist in any table in my database??
You don't define the datatype of a column like that. You let the view use the underlying datatype like this.
ALTER VIEW seat_availability AS
SELECT flightid
, flightdate
, maxcapacity
, bookedseats
, availableseats
FROM flight
Or if you need to explicitly change the datatype you need to use CONVERT like this.
ALTER VIEW seat_availability AS
SELECT flightid
, flightdate
, maxcapacity
, bookedseats = convert(varchar(10), bookedseats)
, availableseats = convert(varchar(10), availableseats)
FROM flight
Try this to add fake columns to the view:
ALTER VIEW [dbo].[view_seat_availability]
AS
SELECT flightid
,flightdate
,maxcapacity
,CAST(NULL AS VARCHAR(10)) AS 'bookedseats'
,CAST(NULL AS VARCHAR(10)) AS 'availableseats'
FROM flight
I'm trying to change the date format of a column stored in a view by doing an ALTER VIEW statement, but it's not working and I'm not sure why.
My query:
ALTER VIEW v_cust_invoices
AS
SELECT
FORMAT(INV_DATE,'MM-dd-yy') as INV_DATE
FROM
v_cust_invoices
I always get the error
View or function 'v_cust_invoices' contains a self-reference. Views or functions cannot reference themselves directly or indirectly
I'm trying to change the date format of INV_DATE to mm-dd-yy (it's currently yy-mm-dd). Can someone help me? Not sure what I'm doing wrong.
Edit: If I do
ALTER VIEW v_cust_invoices
AS
SELECT FORMAT(INV_DATE,'MM-dd-yy') as INV_DATE
FROM INVOICE
instead, it deletes all of the columns except for INV_DATE.
View definition:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE VIEW [dbo].[v_cust_invoices] AS
SELECT
CUSTOMER.CUST_NUM, CUST_LNAME,
CUST_BALANCE, INV_NUM, INV_DATE, INV_AMOUNT
FROM
CUSTOMER, INVOICE
GO
You must change the query so that it does not reference itself.
Look at the current definition of the v_cust_invoices view, at its FROM clause. You will see a reference to a table or to some other view. replace the last line in your query with the last line below, substituting the name of the table (or other view) this view gets it's data from.
ALTER VIEW v_cust_invoices
AS
SELECT FORMAT(INV_DATE,'MM-dd-yy') as INV_DATE,
[Plus all the rest of the output columns
from CURRENT definition of v_cust_invoices]
FROM [here Put the table or other view that is in current view definition]
or, now that op has posted complete view definition:
ALTER VIEW [dbo].[v_cust_invoices] AS
SELECT FORMAT(INV_DATE,'MM-dd-yy') INV_DATE,
CUSTOMER.CUST_NUM, CUST_LNAME,
CUST_BALANCE, INV_NUM, INV_DTE, INV_AMOUNT
FROM CUSTOMER, INVOICE
GO
I have an assignment to change the existing date format in an existing T-SQL view statement. Where the date format is set to YYYY-MM-DD 00:00:00.000 the task is to change is to ALTER VIEW to MM-DD-YY formatting. I'm lost on this one.
USE Ch8_simpleco
ALTER VIEW
AS invoice
SELECT INV_DATE
SET INV_DATE (MMDDYY)
FROM dbo.v_cust_invoices;
You are probably looking for something like this:
ALTER VIEW invoice
AS
SELECT COVERT(char(8), INV_DATE, 10) -- will get you dd-MM-yy (no century!)
FROM dbo.v_cust_invoices
You can use FORMAT() like this:
ALTER VIEW invoice
AS
SELECT FROMAT(INV_DATE,'MM-dd-yy') as INV_DATE
FROM dbo.v_cust_invoices
I have a column BirthDate in a table that is using the datetime data type. Currently, the values resemble the format 1987-12-30 00:00:00.000.
I would like to update all the rows of this table, changing them to the following format with the date data type: 1987-12-30
I can run a SELECT...
SELECT CONVERT(date, BirthDate) FROM CUSTOMERLIST
But this is only affecting the display. I would like for it to update the entire column and also change the data type of that attribute as well. Any assistance would be greatly appreciated!
You will need to ALTER the table:
ALTER TABLE CUSTOMERLIST ALTER COLUMN BirthDate date not null
See Sql Fiddle with demo
I need to use the clock on my SQL Server to write a time to one of my tables, so I thought I'd just use GETDATE(). The problem is that I'm getting an error because of my INSTEAD OF trigger. Is there a way to set one column to GETDATE() when another column is an identity column?
This is the Linq-to-SQL:
internal void LogProcessPoint(WorkflowCreated workflowCreated, int processCode)
{
ProcessLoggingRecord processLoggingRecord = new ProcessLoggingRecord()
{
ProcessCode = processCode,
SubId = workflowCreated.SubId,
EventTime = DateTime.Now // I don't care what this is. SQL Server will use GETDATE() instead.
};
this.Database.Add<ProcessLoggingRecord>(processLoggingRecord);
}
This is the table. EventTime is what I want to have as GETDATE(). I don't want the column to be null.
And here is the trigger:
ALTER TRIGGER [Master].[ProcessLoggingEventTimeTrigger]
ON [Master].[ProcessLogging]
INSTEAD OF INSERT
AS
BEGIN
SET NOCOUNT ON;
SET IDENTITY_INSERT [Master].[ProcessLogging] ON;
INSERT INTO ProcessLogging (ProcessLoggingId, ProcessCode, SubId, EventTime, LastModifiedUser)
SELECT ProcessLoggingId, ProcessCode, SubId, GETDATE(), LastModifiedUser FROM inserted
SET IDENTITY_INSERT [Master].[ProcessLogging] OFF;
END
Without getting into all of the variations I've tried, this last attempt produces this error:
InvalidOperationException
Member AutoSync failure. For members to be AutoSynced after insert, the type must either have an auto-generated identity, or a key that is not modified by the database after insert.
I could remove EventTime from my entity, but I don't want to do that. If it was gone though, then it would be NULL during the INSERT and GETDATE() would be used.
Is there a way that I can simply use GETDATE() on the EventTime column for INSERTs?
Note: I do not want to use C#'s DateTime.Now for two reasons:
1. One of these inserts is generated by SQL Server itself (from another stored procedure)
2. Times can be different on different machines, and I'd like to know exactly how fast my processes are happening.
Bob,
It seems you are attempting to solve two different problems here. One of which has to do with a L2S error with an Instead Of trigger and another with using the date on the SQL Server box for your column. I think you might have problems with Instead of Triggers and L2S. You might want to try an approach that uses an After trigger, like this. I think this will solve both your problems.
ALTER TRIGGER [Master].[ProcessLoggingEventTimeTrigger]
ON [Master].[ProcessLogging]
AFTER INSERT
AS
BEGIN
UPDATE [Master].[ProcessLogging] SET EventTime = GETDATE() WHERE ProcessLoggingId = (SELECT ProcessLoggingId FROM inserted)
END
Don't use a trigger, use a defualt:
create table X
(id int identity primary key,
value varchar(20),
eventdate datetime default(getdate()))
insert into x(value) values('Try')
insert into x(value) values('this')
select * from X
It's much better.
Have you tried using a default value of (getdate()) for the EventTime colum?
You wouldn't then need to set the value in the trigger, it would be set automatically.
A default value is used when you don't explicitly supply a value, e.g.
INSERT INTO ProcessLogging (ProcessLoggingId, ProcessCode, SubId, LastModifiedUser)
SELECT ProcessLoggingId, ProcessCode, SubId, LastModifiedUser FROM inserted
Bob,
I see it is better to don't use triggers in SQL server; it have a lot of disadvantage and not recommended for database performance enhancements. Please check SQL Authority blog for more information about the Triggers problems.
You can achieve what you want without Triggers using the following steps:
Change Eventime column to allow null
Set Eventtime column Default Value to GetDate(). So it always will have a the current insertion value.
Don't set Eventtime value to DateTime.Now from your LinqToSQL code, so it will take the default value in the SQL Server.