Dynamic Datasource in SQL Server Stored Procudure

怎甘沉沦 提交于 2019-12-02 09:51:17

Read up on how to create dynamic SQL, particularly sp_executesql. This should get you started:

DECLARE @theSql varchar(1000)
DECLARE @installId int
SET @installId = 1
SET @theSql = 'SELECT COUNT(*) FROM dbo.Installation' + CAST(@installId as nvarchar) + '.Names'
EXEC  (@theSql)

You have to use dynamic SQL to do that. Table names and database names cannot be resolved at runtime in any other way.

Here is a good introduction to this technique by Scott Mitchell.

As often, the answer to such a question is dynamic SQL:

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE GetInstallationCount
-- Add the parameters for the stored procedure here
@installId int=0
AS
BEGIN
  SET NOCOUNT ON;
  DECLARE @sql nvarchar(MAX)

  SET @sql = 'select count(*) from dbo.Installation' + Cast(@installId as nvarchar) + '.Names'
  EXECUTE dbo.sp_executesql @sql

END
GO

Definately could be done by building up the select string dynamically and executing but it would be nasty.

You could get very flashy and try create synonyms of the fly, use them in the queries and then drop them but I'm not sure it would be worth it.

Use synonyms. For example this sets synonym dbo.MySpecialTable to point to table dbo.SomeTable in database DB_3.

IF object_id(N'SN', N'dbo.MySpecialTable') IS NOT NULL 
        DROP SYNONYM dbo.MySpecialTable
CREATE SYNONYM dbo.MySpecialTable FOR [DB_3].[dbo].[SomeTable]

With this in place, write all your queries to use synonyms instead of real table names. Synonyms have DB scope, so manage "target switching" at one place, maybe in a stored procedure.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!