我正在尝试创建一个简单的脚本,将复杂视图的结果转储到表中以进行报告.我使用同义词来简化视图和表名的调整.
我们的想法是,脚本的用户可以将他们想要用作的视图的名称作为源,并将目标报告表的名称放在它们开始和离开的位置.如果该表不存在,那么脚本应该创建它.如果表已经存在,那么脚本应该只复制视图中尚未包含在表中的记录.
下面的脚本涵盖了所有这些要求,但我找不到一种很好的方法来检查同义词后面的表是否已经存在:
CREATE SYNONYM SourceView FOR my_view
CREATE SYNONYM TargetReportingTable FOR my_table
-- Here's where I'm having trouble, how do I check if the underlying table exists?
IF (SELECT COUNT(*) FROM information_schema.tables WHERE table_name = TargetReportingTable) = 0
BEGIN
-- Table does not exists, so insert into.
SELECT * INTO TargetReportingTable FROM SourceView
END
ELSE
BEGIN
-- Table already exists so work out the last record which was copied over
-- and insert only the newer records.
DECLARE @LastReportedRecordId …
Run Code Online (Sandbox Code Playgroud)