Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

send datepart as parameter from a table to DATEADD function in sql server

Tags:

sql-server

I Have to Update City.Date in City table and I have columns in the table like Interval and Period in the City table.

Interval column contains values like yy,ww,dd,qq,etc and Period column contains values like 1,2,3.

I am trying to update City.Date like this:

UPDATE City 
SET City.date = DATEADD(City.Interval, City.Period, City.date)
WHERE CityId = 13

It is getting error like:

City.Interval is not recognized DATEADD option.

How can I update City.Date using City.Interval, City.Period and City.date?

like image 858
Avinash Avatar asked Aug 02 '11 07:08

Avinash


People also ask

Can you use Datepart in SQL?

The DATEPART SQL function returns an integer value of specific interval. We will see values for this in the upcoming section. Date: We specify the date to retrieve the specified interval value. We can specify direct values or use expressions to return values from the following data types.

Can we use Datepart in where clause?

Note that you can use the DATEPART() function in the SELECT , WHERE , HAVING , GROUP BY , and ORDER BY clauses.


1 Answers

You can't parameterise the interval bit

UPDATE City 
SET date = CASE Interval
              WHEN 'yy' THEN DATEADD(yy, Period, date)
              WHEN 'ww' THEN DATEADD(ww, Period, date)
              WHEN 'dd' THEN DATEADD(dd, Period, date)
              WHEN 'qq' THEN DATEADD(qq, Period, date)
              WHEN ...
           END
WHERE CityId =13
like image 78
gbn Avatar answered Sep 28 '22 05:09

gbn