我正在为数据迁移编写存储过程。在那里,我需要将表及其整个数据从其他数据库复制到当前数据库的临时表。但是,数据库名称将作为参数。然后我需要处理复制的数据。但是,我不知道如何使用动态数据库名称。
CREATE PROCEDURE [dbo].[MGRT]
@DBName VARCHAR(50)
AS
BEGIN
SET NOCOUNT ON;
IF OBJECT_ID('tempdb..#TMPCH') IS NOT NULL
DROP TABLE #TMPCH;
SELECT * INTO #TMPCH FROM MDDX.dbo.CH ORDER BY MDate,Mtime
DECLARE @count INT = 0
DECLARE @curRow INT = 0
SELECT @count = COUNT(*) FROM #TMPCH
WHILE @curRow <= @count
BEGIN
DECLARE @lastDate NVARCHAR(10) = '-'
SET @lastDate = (SELECT TOP 1 To_Date FROM CH ORDER BY SysKey DESC)
IF @lastDate = '' OR @lastDate IS NULL
BEGIN
SET @lastDate = '-'
PRINT @lastDate
END
INSERT INTO CH(syskey,CurCode,CurDesc,CurSymbol,CurRate,From_Date,To_Date,userid,username)
(SELECT @curRow,CurCode,CurDesc,CurSymbol,CURRATE,@lastDate,MDate,'admin','Administrator'
FROM (SELECT *,ROW_NUMBER() OVER(ORDER BY MDate,MTime) AS rowNo FROM #TMPCH) AS TMP WHERE rowNo = @curRow)
SET @curRow = @curRow + 1
END
END
我需要使用@DBName而不是MDDX来获取数据。
谢谢!
答案 0 :(得分:0)
您需要使用动态查询,如下所示;
CREATE PROCEDURE [dbo].[MGRT]
@DBName VARCHAR(50)
AS
BEGIN
SET NOCOUNT ON;
DECLARE sSQL as varchar(200)
IF OBJECT_ID('tempdb..#TMPCH') IS NOT NULL
DROP TABLE #TMPCH;
sSQL = 'SELECT * INTO #TMPCH FROM @DBName.dbo.CH ORDER BY MDate,Mtime'
Exec (sSQL)
DECLARE @count INT = 0
DECLARE @curRow INT = 0
SELECT @count = COUNT(*) FROM #TMPCH
WHILE @curRow <= @count
BEGIN
DECLARE @lastDate NVARCHAR(10) = '-'
SET @lastDate = (SELECT TOP 1 To_Date FROM CH ORDER BY SysKey DESC)
IF @lastDate = '' OR @lastDate IS NULL
BEGIN
SET @lastDate = '-'
PRINT @lastDate
END
INSERT INTO CH(syskey,CurCode,CurDesc,CurSymbol,CurRate,From_Date,To_Date,userid,username)
(SELECT @curRow,CurCode,CurDesc,CurSymbol,CURRATE,@lastDate,MDate,'admin','Administrator'
FROM (SELECT *,ROW_NUMBER() OVER(ORDER BY MDate,MTime) AS rowNo FROM #TMPCH) AS TMP WHERE rowNo = @curRow)
SET @curRow = @curRow + 1
END
END