SQL SELECT,CASE,BETWEEN INTO语句

时间:2016-01-11 16:29:25

标签: sql sql-server tsql case between

我有一个SQL查询,它比较2个表以检查登录时间和计划是否已关闭以填充具有int值的第3个表。我得到了它,但我正在尝试为select命令添加其他变体。

以下是有效的代码:

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语句。这表示命令运行但是从不创建Integers表。这可以在1个SQL命令中完成吗?此外,我还需要添加大约4个BETWEEN查询来处理此命令。

1 个答案:

答案 0 :(得分: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字符串与仅按原样执行SELECT语句?