创建动态查询

时间:2016-12-06 03:22:33

标签: sql sql-server database dynamic

我已经制作了这样的存储过程..

CREATE PROCEDURE [dbo].[sp_dataPull] @serverName nvarchar(30), @dbName nvarchar (30), @serverName2 nvarchar(30), @dbName2 nvarchar (30)

    INSERT INTO sampleDatabase.dbo.WorkFlowCopy
      ([ServerName]
      ,[DBName]
      ,[ID]
      ,[ActivityDefinitionID]
      ,[ParentID]
      ,[Caption]
      ,[Description]
      ,[ShortDescription]

(SELECT @serverName, @dbName, sdb1.* from OPENDATASOURCE('SQLOLEDB',
'Data Source=phmnldb16\eaudit;user id=XXXX;password=XXXX').AUDIT_FSA_170_001.AUD170.Workflow sdb1)

UNION ALL

(SELECT @serverName2, @dbName2, sdb2.* from OPENDATASOURCE('SQLOLEDB',
'Data Source=phmnldb16\eaudit;user id=XXXX;password=XXXX').AUDIT_FSA_170_002.AUD170.Workflow sdb2)

此查询的功能是将数据从另一台服务器移动到特定的表中。现在,请注意我下面有2个SELECT语句,我有4个参数。这是因为我合并了2个表并将其移动到另一个表中。

此查询的问题在于它是静态的。如果我需要组合3个或更多表格怎么办?然后我必须创建另一个(下面的SELECT和UNION ALL语句,并添加另外两个或更多参数)..我想让它动态。

1 个答案:

答案 0 :(得分:0)

尝试如下:

CREATE PROCEDURE SP_DATAPULL @SERVER NVARCHAR(30),@DB NVARCHAR(30)
AS 
BEGIN
DECLARE @SERVER NVARCHAR(MAX)='SERVER1,SERVER2,SERVER3,SERVER4,SERVER5'
DECLARE @DB NVARCHAR(MAX)='DB1,DB2,DB3,DB4,DB5'
DECLARE @SRV NVARCHAR(MAX),@DBN NVARCHAR(MAX),@QUERY NVARCHAR(MAX)
DECLARE @TEMP TABLE(SERVERNAME VARCHAR(100),DB VARCHAR(100))

WHILE(SELECT CHARINDEX(',',@SERVER))>0
BEGIN
SET @SRV=(SELECT SUBSTRING(@SERVER,0,CHARINDEX(',',@SERVER)))
SET @SERVER=SUBSTRING(@SERVER,LEN(@SRV)+2,LEN(@SERVER))

SET @DBN=(SELECT SUBSTRING(@DB,0,CHARINDEX(',',@DB)))
SET @DB=SUBSTRING(@DB,LEN(@DBN)+2,LEN(@DB))
INSERT INTO @TEMP VALUES (@SRV,@DBN )
END
INSERT INTO @TEMP VALUES (@SERVER,@DB )

SET @QUERY=' INSERT INTO sampleDatabase.dbo.WorkFlowCopy
      ([ServerName]
      ,[DBName]
      ,[ID]
      ,[ActivityDefinitionID]
      ,[ParentID]
      ,[Caption]
      ,[Description]
      ,[ShortDescription] '

DECLARE C CURSOR FOR
SELECT SERVERNAME,DB FROM @TEMP
OPEN C
FETCH NEXT FROM C INTO @SERVER,@DB
WHILE @@FETCH_STATUS=0
BEGIN

SET @QUERY=@QUERY+'(SELECT '''+@SERVER+''', '''+@DB+''', sdb1.* from OPENDATASOURCE(''SQLOLEDB'',
''Data Source=phmnldb16\eaudit;user id=XXXX;password=XXXX'').AUDIT_FSA_170_001.AUD170.Workflow sdb1) '

FETCH NEXT FROM C INTO @SERVER,@DB
END
CLOSE C
DEALLOCATE C
SET @QUERY=SUBSTRING(@QUERY,0,LEN(@QUERY)-LEN('UNION ALL'))
PRINT @QUERY
EXEC(@QUERY)
END