2015-06-20 91 views
0

基本上,我需要爲植物及其收穫日期製作數據庫。例如,所有植物的表格。如何存儲日期並在sql server中進行比較?

CREATE TABLE plant 
    (
     plant_name NVARCHAR(20) NOT NULL 
           PRIMARY KEY , 
     best_to_harvest_day INT NOT NULL , 
     best_to_harvest_month NVARCHAR(15) 
    ) 

例植物項:羅斯12月16日 而另一臺名爲收穫 當多個收穫的植物和日期,他們收穫的時候。

CREATE TABLE harvests 
(
    plant_name nvarchar(20) NOT NULL FOREIGN KEY REFERENCES plant(plant_name), 
    amount int NOT NULL, 
    havested_day int NOT NULL, 
    harvested_month nvarchar(15), 
    harvested year int NOT NULL 
) 

而且這種方法做的工作,因爲我可以做一個SQL查詢來比較其在植物的最佳時機等 收穫但是,這不是有一個整潔的方式嗎? 是這樣的:(使用日期)

CREATE TABLE plant 
(
    plant_name NVARCHAR(20) NOT NULL 
          PRIMARY KEY , 
    best_to_harvest DATE --But here should only be day and month, not year. 
) 

CREATE TABLE harvests 
(
    plant_name NVARCHAR(20) NOT NULL 
          FOREIGN KEY REFERENCES plant (plant_name) , 
    amount INT NOT NULL , 
    harvested DATE --But here i need full date year,day,month 
) 

底線是,我需要對它們進行比較。 好吧,我想我可以使用EXTRACT(單位從日期) ,然後比較他們,但問題仍然存在,如何使植物表日期不包括年?

+0

比較怎麼樣?你想要做什麼? – nhgrif

+0

您可以使用0年和比較使用dateadd(年,年(日期),日期) - 以便它也將成爲0 –

+0

我需要檢查,植物是否在最佳時間收穫。簡單的sql select查詢... –

回答

0

首先,將日期部分存儲爲數字並檢查其值。這並不完美,但可能不夠好:

CREATE TABLE plant (
    plant_id int not null PRIMARY KEY, 
    plant_name nvarchar(20) NOT NULL UNIQUE, 
    best_to_harvest_day int NOT NULL, 
    best_to_harvest_month int not NULL, 
    check (best_to_harvest_day between 1 and 31), 
    check (best_to_harvest_month between 1 and 12) 
); 

請注意包含整數標識主鍵。建議這樣做,因爲整數對於外鍵引用更高效。

然後使用date的收穫:

CREATE TABLE harvests (
    harvest_id int not null primary key, 
    plant_id int NOT NULL FOREIGN KEY REFERENCES plant(plant_id), 
    amount int NOT NULL, 
    harvested date --But here i need full date year,day,month 
); 

你可以這樣做:

select h.*, 
     (case when p.best_to_harvest_day = day(h.harvest_day) and 
        p.best_to_harvest_month = month(h.harvest_month) 
      then 'Y' else 'N' 
     end) 
from harvest h join 
    plant p 
    on h.plant_id = p.plant_id;