Domanda

I have to create a new table in my SQL Server 2008 and set my date column to auto increment by 1 day from Getdate().

The first entry should insert using the current date, the second entry should use tomorrow's date and the third entry the day after tomorrow's date and so on.

And I also want to know if there is any way to do this manually with update command that it put today's date in 1st column and tomorrows in 2nd.

È stato utile?

Soluzione 3

I got my answer in a simple script:

update  t2 
set     DateColumn = DATEADD(day, rn-1, '1970-01-01')
from    @t2 t2
join    (
        select  ROW_NUMBER() over (order by id) rn
        ,       id
        from    @t2 
        ) t2_numbered
on      t2_numbered.id = t2.id

select * from @t2

Altri suggerimenti

Regardless of exactly what you need to do, this function will allow you to do the date incrementing.

http://technet.microsoft.com/en-us/library/ms186819.aspx

Example for generating a date one day in the future:

SELECT DATEADD(dd,1,GETDATE());

**

1) If you need to generate an incremented date on each row insert, you could certainly use a trigger and do the update at that time.

Similar question with example of using trigger to do a row update

2) If you need to generate multiple rows of data and fill the table, you could do your INSERT operation, and follow it with an update to generate the dates. Knowing nothing of your table structure, perhaps something like this would work:

UPDATE T 
SET T.date_col = 
(
  SELECT 
    TOP(1) DATEADD(dd,1,date_col) 
  FROM myTable
  WHERE
    ID = T.ID - 1
)
FROM myTable T
WHERE
  T.date_col IS NULL;

Just put a logic!

insert into myTbl
select Isnull(max(date_column),getdate()) + 1 from myTbl

For Update, try this, abc is name of actual table

;with cte as
(
select ROW_NUMBER() over(order by date_col asc) as rno
    ,date_col
 from abc
)
update  cte  set date_col = Dateadd(dd,rno-1,getdate())
 from cte
where cte.date_col is null
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top