在查询中动态指定数据库名称

时间:2012-08-01 20:30:52

标签: sql

我有一个Monster SQl查询,它查找从暂存数据库中获取数据,在目标数据库上进行连接并在目标表上插入/更新数据。

简化格式就像这样

MERGE INTO SOURCEDB.SCHEMA.DESTIANTIONTABLE AS TARGET
USING (SELECT COLA, COLB, COLC FROM STAGEDB.SCHEMA.SOURCE A INNER JOIN SOURCEDB.Schema,TABLEA) AS SOURCE
ON TARGET.ID = SOURCE.ID
WHEN MATCHED THEN UPDATE--

WHEN NOT MATCHED INSERT

我可以动态设置STAGING DB Name,查询很大,所以我不想使用exec SQl语法。 有什么建议吗?

2 个答案:

答案 0 :(得分:3)

您应该能够使用同义词。

DROP SYNONYM syn_a;
CREATE SYNONYM a FOR STAGEDB.SCHEMA.SOURCE;
DROP SYNONYM syn_b;
CREATE SYNONYM b FOR STAGEDB.SCHEMA.TABLEA;
DROP SYNONYM syn_target;
CREATE SYNONYM target FOR SOURCEDB.SCHEMA.DESTINATIONTABLE;

MERGE INTO syn_target as TARGET
USING (SELECT COLA, COLB, COLC FROM syn_a as A INNER JOIN syn_b as B
) AS SOURCE
ON TARGET.ID = SOURCE.ID
WHEN MATCHED THEN UPDATE--

WHEN NOT MATCHED INSERT

答案 1 :(得分:0)

Sql Server不喜欢用@variables替换数据库名称,模式或表,这可能就是你所追求的,所以你需要通过使用EXEC来进行动态sql路由。

在使用nvarchar(max)数据类型时,在Sql Server 2005及更高版本中执行非常大的sql语句没有问题。限制是2Gb或服务器内存中的较小者。

Declare @Sql nvarchar(max)
set @Sql = '
MERGE INTO SOURCEDB.SCHEMA.DESTIANTIONTABLE AS TARGET
USING (SELECT COLA, COLB, COLC FROM '+@StageDB+'.SCHEMA.SOURCE A INNER JOIN SOURCEDB.Schema,TABLEA) AS SOURCE
ON TARGET.ID = SOURCE.ID
WHEN MATCHED THEN UPDATE--

WHEN NOT MATCHED INSERT ...
'
exec (@Sql)