2012-03-26 67 views
0

我不擅長t-sql,所以我需要幫助。如果在sql中構建

我有這樣的代碼,我寫我自己,但怎麼寫,我想我不知道(與英語難過)

declare @questionid int 
set @questionid = 22 

declare @providerid int 
set @providerid = 189 

select [closed] into #question from [Data].[dbo].[Question] where [questionid] = @questionid 

-- and here, if [closed] is null I must write in the question table current date GETDATE() 
UPDATE [Data].[dbo].[Question] SET [closed] = GETDATE() WHERE [questionid] = @questionid and [providerid] = @providerid 

-- or, if [closed] is not null I must write there null 
UPDATE [Data].[dbo].[Question] SET [closed] = null WHERE [questionid] = @questionid and [providerid] = @providerid 

drop table #question 

我怎麼能這樣做?

+1

它能夠更好地去情況時,這是緊湊...並保存額外的行,使代碼清晰... – 2012-03-26 13:34:20

+0

@Pranay林蛙你是正確的 – Wachburn 2012-03-26 13:40:44

回答

1

你並不需要爲這個

declare @questionid int 
set @questionid = 22 

declare @providerid int 
set @providerid = 189 

declare @closed datetime 
select @closed = [closed] from [Data].[dbo].[Question] where [questionid] = @questionid 

-- and here, if [closed] is null I must write in the question table current date GETDATE() 
IF @closed IS NULL 
    UPDATE [Data].[dbo].[Question] SET [closed] = GETDATE() WHERE [questionid] = @questionid and [providerid] = @providerid 
ELSE 
-- or, if [closed] is not null I must write there null 
    UPDATE [Data].[dbo].[Question] SET [closed] = null WHERE [questionid] = @questionid and [providerid] = @providerid 

我必須說,我不明白你正在努力實現的邏輯臨時表...

+0

謝謝,那是我需要的。 @closed變量不是位,它的日期時間。如果用戶關閉關閉按鈕 - 問題將關閉,如果用戶在同一個按鈕上(與另一個文本「打開」)關閉 - 問題將打開。謝謝。 – Wachburn 2012-03-26 13:37:10

+0

我編輯了修復變量聲明的答案。只是爲了讓你知道,如果你在IF中有多個句子,你必須使用BEGIN和END來包含它們。另外,在這種情況下,可以使用一個單獨的UPDATE而不需要使用IF,就像@PranayRana所說的那樣,但是當你問如何使用IF來學習它時,我回答了這個問題。 – 2012-03-26 13:42:48

+0

你是非常準時的男人) – Wachburn 2012-03-26 13:45:04

1

利用case when可以輕鬆實現你的任務..

UPDATE [Data].[dbo].[Question] 
SET [closed] = CASE 
      WHEN [closed] is null THEN GetDate() 
      ELSE null 
      END 
WHERE [questionid] = @questionid 
    and [providerid] = @providerid 
+0

我也必須做相反的操作。 Null到datetime和datetime爲null。 AlejoBrz給出了工作代碼。 – Wachburn 2012-03-26 13:33:39