2016-01-11 225 views
0

我有一個SQL查詢比較2個表來檢查登錄時間和日程表是否關閉,以便用int值填充第三個表。我得到它的工作,但我試圖添加其他變化到選擇命令。SQL SELECT,CASE,BETWEEN INTO語句

這裏是工作的代碼:

DECLARE @sqlSelect varchar(max) 
SET @sqlSelect = 'SELECT loginlogout.[Agent Name], case when loginlogout.[Login Time] = Schedules$.StartTime then 0 else 1 end as LoginInc into Integers FROM loginlogout JOIN Schedules$ on loginlogout.[Agent Name] = Schedules$.AgentName' 

EXEC(@sqlSelect) 
GO 

什麼我想補充的是這樣的:

DECLARE @six varchar(max) 
DECLARE @sixo varchar(max) 
DECLARE @sixnerdy varchar(max) 
DECLARE @sqlSelect varchar(max) 
SET @six = '[6:00AM]' 
SET @sixo = '[6:05AM]' 
SET @sixnerdy = '[6:30AM]' 
SET @sqlSelect = 'SELECT loginlogout.[Agent Name], case when loginlogout.[Login Time] = Schedules$.StartTime then 0 when [Login Time] BETWEEN '+ @sixo +' and '+ @sixnerdy +' then 1 else 1 end as LoginInc into Integers FROM loginlogout JOIN Schedules$ on loginlogout.[Agent Name] = Schedules$.AgentName' 

EXEC(@sqlSelect) 
GO 

當運行這個查詢,我得到錯誤味精207無效列名。因此我嘗試過:

SET @sqlSelect = 'SELECT loginlogout.[Agent Name], case when loginlogout.[Login Time] = Schedules$.StartTime then 0 when [Login Time] BETWEEN '+ @sixo +' and '+ @sixnerdy +' then 1 else 1 end as LoginInc into Integers' 

刪除FROM語句。這表示該命令運行,但整數表永遠不會創建。這可以在1個SQL命令中完成嗎?此外,我還需要添加約4個以上的BETWEEN查詢來加強此命令。

+1

'6:00 AM'是一個奇怪的字段名稱。這真的是這個領域的名字嗎? –

+0

@ConradFrix,'6:00 AM'不用作字段名稱,它在'between'之間使用' – HoneyBadger

+4

@HoneyBadger注意在6:00 AM前後的'[]'。由於它連接到SQL字符串,我希望它被視爲字段名稱而不是值 –

回答

1

由於時間未包含在單引號中,初看一眼就會質疑沒有問題。有這樣的工作嗎?

DECLARE @six varchar(max) 
DECLARE @sixo varchar(max) 
DECLARE @sixnerdy varchar(max) 
DECLARE @sqlSelect varchar(max) 
SET @six = '''6:00AM''' 
SET @sixo = '''6:05AM''' 
SET @sixnerdy = '''6:30AM''' 
SET @sqlSelect = 'SELECT loginlogout.[Agent Name], case when loginlogout.[Login Time] = Schedules$.StartTime then 0 when [Login Time] BETWEEN '+ @sixo +' and '+ @sixnerdy +' then 1 else 1 end as LoginInc into Integers FROM loginlogout JOIN Schedules$ on loginlogout.[Agent Name] = Schedules$.AgentName' 

EXEC(@sqlSelect) 
GO 

雖然這一切似乎仍然有點笨拙。是否有理由EXEC一個SQL字符串vs只是按原樣執行SELECT聲明?