我需要一个数据库变量,因为我正在访问数据的表将在各种数据库中,例如dBase1,dBase2等。我不能在字符串中使用Select ...因为我想使用Select声明到游标中,这似乎不允许使用字符串和exec命令。这是一个不起作用的例子。任何建议都表示赞赏......
DECLARE @fromDBase varchar(10), @FundCD char(4), @actID INT,
@PortCode char(4), @FundDecm INT, @PlanCd char(6)
set @FundCD = 'F0XX'
set @actID = 11135408
set @PortCode = 'P001'
set @FundDecm = 3
set @PlanCd = 'XXX001'
DECLARE csFin cursor STATIC LOCAL for
SELECT PortionCode, CashValue, UnitValue, CostValue, UniqueID
from (SELECT DatabaseName FROM [dBase1].[dbo].mPTLDetail WHERE plancode = @PlanCd)
WHERE AccountID = @actID
AND FundCode = @FundCd
AND UnitValue != 0
AND (Cast(Str(UnitValue, 12, @FundDecm) as money) - UnitValue) != 0
答案 0 :(得分:0)
我认为您需要构建一个动态语句并调用exec sp_executesql来执行它。 不知道这会如何影响光标,我对它们不太熟悉。
DECLARE @fromDBase varchar(10), @FundCD char(4), @actID INT,
@PortCode char(4), @FundDecm INT, @PlanCd char(6),
@sqlstatement nvarchar(4000)
set @FundCD = 'F0XX'
set @actID = 11135408
set @PortCode = 'P001'
set @FundDecm = 3
set @PlanCd = 'XXX001'
SELECT @fromDBase = DatabaseName FROM [dBase1].[dbo].mPTLDetail WHERE plancode = @PlanCd
set @sqlstatement = 'DECLARE csFin cursor STATIC LOCAL for SELECT PortionCode, CashValue,
UnitValue, CostValue, UniqueID from' + @fromDBase + 'WHERE AccountID = ' + @actID + ' AND
FundCode = ' + @FundCd + ' AND UnitValue != 0 AND (Cast(Str(UnitValue, 12, ' + @FundDecm
+') as money) - UnitValue) != 0'
exec sp_executesql @sqlstatement
答案 1 :(得分:0)
可以使用游标变量和sp_executesql
动态分配游标。
CREATE PROCEDURE GetData
@FundCD char(4), @actID int, @PortCode char(4), @FundDecm int,
@PlanCd char(6)
AS
DECLARE @fromDBase varchar(10), @query nvarchar(max), @cursor cursor
SET @fromDBase =
(
SELECT DatabaseName
FROM [dBase1].[dbo].mPTLDetail
WHERE plancode = @PlanCd
)
SET @query = N'
SET @cursor = CURSOR FOR
SELECT PortionCode, CashValue, UnitValue, CostValue, UniqueID
FROM ' + QUOTENAME(@fromDBase) + '.[dbo].[Table1]
WHERE AccountID = @actID
AND FundCode = @FundCd
AND UnitValue != 0
AND (Cast(Str(UnitValue, 12, @FundDecm) as money) - UnitValue) != 0;
OPEN @cursor;'
EXEC sp_executesql @query,
N'@FundCD char(4), @actID int, @FundDecm int, @cursor cursor out',
@FundCD, @actID, @FundDecm, @cursor out
FETCH NEXT FROM @cursor