在开始这个问题之前,我会说我的sql不是很好:)
我们正在尝试通过两个冗余表在sql中构建一个双缓冲的实现。在任何时候,一个表是活动的,另一个是非活动的。这些表由一个视图访问,我们在重新加载数据后切换该视图。当我们重新加载时,我们想要在非活动表上执行操作,然后在完成时切换活动缓存。
我们有很多代码,看起来有点像:
IF @activeCache = 0
BEGIN WORK ON TABLE 1 AS IT IS INACTIVE
ELSE
BEGIN WORK ON TABLE 0 AS IT IS INACTIVE问题是括号之间的代码不是微不足道的,所以我们最终复制了代码,其中唯一的区别是正在操作的表。我们认为表参数可能会有所帮助,但您不能将其插入其中(这是我们需要做的)。我现在唯一的想法是使用T4模板为我们生成crud,但我似乎不能让它们在数据库项目中工作。
有没有什么sql结构可以帮助我们?如果可能的话,我们不希望使用动态sql。
发布于 2013-02-28 21:29:00
您可以使用CREATE SYNONYM有效地为对象创建永久别名(或“同义词”)。您可以运行您的逻辑一次,以确定哪个表为目标,然后运行:
CREATE SYNONYM WorkingTable FOR Table1
CREATE SYNONYM MainTable FOR Table2然后切换:
DROP SYNONYM WorkingTable
DROP SYNONYM MainTable
CREATE SYNONYM WorkingTable FOR Table2
CREATE SYNONYM MainTable FOR Table1在您的脚本中的其他地方,您可以只引用WorkingTable进行更新,引用MainTable进行读取。
话虽如此,我同意其他质疑这是否是最好的工作方式的评论/答案。
发布于 2013-02-28 20:44:57
使用一个主表和一个临时表,而不是使用两个表并切换视图。
当您准备好将数据迁移到主表时,您可以在原子事务中进行迁移,如下所示。
begin try
begin tran
delete * from MainTable with (tablockx)
insert MainTable
select * from StagingTable with (tablockx)
commit
end try
begin catch
rollback
raiserror('An error occurred swapping staging data', 16,16)
end catch这样,您就可以始终在临时表上工作,因此识别要使用的正确表并不困难。
根据数据的不同,您可能需要对主表进行增量更新:
-- delete rows which no longer exist
delete MainTable
from MainTable
where not exists (select 1 from StagingTable where StagingTable.primaryKey = MainTable.primaryKey)
-- Insert new rows
insert MainTable
select *
from StagingTable
where not exists (select 1 from MainTable where StagingTable.primaryKey = MainTable.primaryKey)
-- update rows which have changed
update MainTable
set
col1 = stagingTable.col1,
col2 = stagingTable.col2
from MainTable inner join StagingTable on StagingTable.primaryKey = MainTable.primaryKey
where 1=2
-- Need to compare every column, only update if one is different
-- Both null counts as the same - compare nullity
OR case when MainTable.col1 is null then 0 else 1 end <> case when StagingTable.col1 is null then 0 else 1 end
OR MainTable.col1 <> StagingTable.col1
OR case when MainTable.col2 is null then 0 else 1 end <> case when StagingTable.col2 is null then 0 else 1 end
OR MainTable.col2 <> StagingTable.col2发布于 2013-02-28 21:07:27
您可以创建以@activeCache为参数的内联表值函数。根据该函数中的参数,从适当的表中选择所有数据。我对性能不太确定。
https://stackoverflow.com/questions/15135798
复制相似问题