我有一个运行良好的存储过程;
ALTER PROCEDURE [dbo].[currentCoForHiLo]
@CoKeyCode Char(50)
BEGIN
SET NOCOUNT ON;
CREATE TABLE ##WrkedOnCo(cKeyCode Char(50), DateInt Int, HighValu Int, LowValu Int)
CREATE CLUSTERED INDEX IDX_CI ON ##WrkedOnCo(DateInt)
INSERT INTO ##WrkedOnCo
SELECT KeyCode, DateAsInt, HighValu, LowValu
FROM EODValuesAU
WHERE KeyCode = @CoKeyCode;
END
该程序从一个表EODValuesAU
获取数据。
我现在有多个表EODValuesAU
,EODValuesUS
,EODValuesUK
。
我尝试将代码更改为以下内容,但查询现在有错误。我想在查询中为表使用变量。有什么方法可以做到这一点。请参阅下面的更改代码;
ALTER PROCEDURE [dbo].[currentCoForHiLo]
@CoKeyCode Char(50), @CounrtyCode Char(10)
AS
BEGIN
SET NOCOUNT ON;
CREATE TABLE ##WrkedOnCo(cKeyCode Char(50), DateInt Int, HighValu Int, LowValu Int)
CREATE CLUSTERED INDEX IDX_CI ON ##WrkedOnCo(DateInt)
INSERT INTO ##WrkedOnCo
SELECT KeyCode, DateAsInt, HighValu, LowValu
FROM 'EODValues' + @CountryCode
WHERE KeyCode = @CoKeyCode;
END
答案 0 :(得分:0)
动态SQL是你的朋友。
而不是INSERT,尝试这样的事情:
DECLARE @sql VARCHAR(400);
SET @sql = 'INSERT INTO ##WrkedOnCo SELECT KeyCode, DateAsInt, HighValu, LowValu FROM EODValues'+@CountryCode+' WHERE KeyCode = @CoKeyCode;';
PRINT @sql; --check its what you want first
--EXEC (@sql);
Damien_The_Unbeliever的评论将是最好的,动态SQL很快就会变得混乱
答案 1 :(得分:0)
-- you Have to Use Dynamic Query to desire Output
ALTER PROCEDURE [dbo].[currentCoForHiLo]
@CoKeyCode NVARCHAR(50),@CounrtyCode NVARCHAR (10)
AS
BEGIN
SET NOCOUNT ON;
CREATE TABLE ##WrkedOnCo(cKeyCode NVARCHAR(50), DateInt Int, HighValu Int, LowValu Int)
CREATE CLUSTERED INDEX IDX_CI ON ##WrkedOnCo(DateInt)
DECLARE @sql VARCHAR(4000)
SET @sql = 'INSERT INTO ##WrkedOnCo
SELECT KeyCode, DateAsInt, HighValu, LowValu FROM EODValues'+@CounrtyCode+' WHERE KeyCode = '''+@CoKeyCode+'''';
PRINT @sql;
EXEC (@sql);
END