我正在尝试从一个表中选择一个值并将其插入另一个表的specfic部分。我有以下sql(mssql 2008)
if exists (select datesubmitted from JADHist where datesubmitted = DATEADD(dd, 0, DATEDIFF(dd, 0, GETDATE()-1)))
Begin
Select JadOPNTotal from JADhist where dateSubmitted = DATEADD(dd, 0, DATEDIFF(dd, 0, GETDATE()-1))
end
else
begin
Select jadopntotal from JADhist where dateSubmitted = DATEADD(dd, 0, DATEDIFF(dd, 0, GETDATE()-2))
end
这总是检索一个数据类型为real的值。我有另一张表,其中有2列,其中一个是小时旁边的小时日期,并且每小时都会有接下来2周的条目。格式为2013-03-26 01:00:00.000,依此类推。我想将上面代码中的值插入到第二个表中一个24小时(24个条目)。 24个时段将从今天早上6点到明天早上6点。
我还有以下代码,测试值为10,只是为了证明代码正确更新opndata。
UPDATE [GasNominations].[dbo].[OPNData]
SET
[Value] = '10'
WHERE NomSubmittedDate between DATEADD(HH, 6, DATEDIFF(dd, 0, GETDATE()))
and DATEADD(HH, 5, DATEDIFF(dd, 0, GETDATE()+1))
GO
我想用if exists语句替换'10'值,但我不能正确使用语法。
答案 0 :(得分:1)
试试这个
declare @total varchar(10)
if exists (select datesubmitted from JADHist
where datesubmitted = DATEADD(dd, 0, DATEDIFF(dd, 0, GETDATE()-1)))
Begin
Select @total = JadOPNTotal from JADhist
where dateSubmitted = DATEADD(dd, 0, DATEDIFF(dd, 0, GETDATE()-1))
end
else
begin
Select @total = jadopntotal from JADhist
where dateSubmitted = DATEADD(dd, 0, DATEDIFF(dd, 0, GETDATE()-2))
end
UPDATE [GasNominations].[dbo].[OPNData]
SET
[Value] = @total
WHERE NomSubmittedDate between DATEADD(HH, 6, DATEDIFF(dd, 0, GETDATE()))
and DATEADD(HH, 5, DATEDIFF(dd, 0, GETDATE()+1))
GO