CREATE VIEW [Myview] AS
SELECT
CASE
WHEN
DATENAME(dw,DATEADD(yy, DATEDIFF(yy, 0, GETDATE()), 0))='Sunday'
THEN
SELECT
cast(DATEPART(yyyy, getdate()-7) as varchar(4)) as YEAR,
RIGHT('00'+cast(DATEPART(ww, getdate()-7) as varchar(2)),2) as WEEK;
ELSE
SELECT
cast(DATEPART(yyyy, getdate()-14) as varchar(4)) as YEAR,
RIGHT('00'+cast(DATEPART(ww, getdate()-14) as varchar(2)),2) as WEEK;
GO
Error while creating: Msg 103010, Level 16, State 1, Line 1 Parse error at line: 8, column: 3: Incorrect syntax near 'SELECT'.
Help me out to fix this error. I want to check if the 1st day of the year is Sunday then I would follow the then statement. Then statement suggest to get week id and year.enter image description here
There are multiple problems with your SQL. Firstly you have 3
SELECTstatements in your query; 2 of which are inside yourCASEExpression. AVIEWis a pseudo table who's definition is defined by a single statement ending in aSELECT. You have 2/3 statements here so it's not a valid definition for aVIEW.Next, as I emphasised,
CASEis an expression in T-SQL, not a Statement. T-SQL does not supportCase(Switch) statements, onlyCASEexpressions.CASEexpressions return a scalar value; not statements, not boolean results. This means that you can only return one atomic value from the expression, and therefore each expressionWHENand theELSEmust result in a scalar value too.Looking at what you've attempted here, however, I'm not even sure it belongs as a
VIEW. It doesn't reference any tables, which normally aVIEWwould. I would, personally, suggest this is better off as a inline table value function, which (if I understand what you are attempting correctly) would look like this:I also tidy up some of your SQL> For example I use the same keywords consistently for the date parts like
YEARandWEEK(you used bothyyandyyyyfor year), and replace the logic that treats dates like anintwith explicitDATEADDlogic, as that works with any date and time data type (not just the old(small)datetimedata types).You would then call the function like so: