2013-10-16 103 views
1

有誰能告訴我這個存儲過程有什麼問題嗎?我只是新的嘗試創建一個新的存儲過程,我已經聲明@ctable。但它不能被發現。請幫我在可變創建存儲過程錯誤

CREATE PROCEDURE [dbo].[sptally] 
    @cfield varchar(80), 
    @ctable varchar(30) 
AS 
BEGIN 
SET NOCOUNT ON; 
    IF OBJECT_ID('dbo.tally') IS NOT NULL DROP TABLE dbo.tally 

    DECLARE @Counter INT = (Select MAX(CAST(@cfield as bigint)) from @ctable) 

    SET ROWCOUNT @Counter 

    SELECT IDENTITY(INT, 1, 1) ID 
    INTO dbo.tally 
    FROM master.sys.all_columns c 
    CROSS JOIN master.sys.all_columns c1 

    SET ROWCOUNT 0 

    -- ADD (unique) clustered index 
    CREATE UNIQUE CLUSTERED INDEX PKC_Tally ON dbo.tally (ID) 
END 
+0

是什麼錯誤消息? –

+0

DECLARE @Counter INT =(從@ctable選擇MAX(CAST(@cfield as bigint)) 無法識別...它說需要聲明 –

回答

1
CREATE PROCEDURE [dbo].[sptally] 
    @cfield varchar(80), 
    @ctable varchar(30) 
AS 
BEGIN 
SET NOCOUNT ON 
    IF OBJECT_ID('dbo.tally') IS NOT NULL DROP TABLE dbo.tally 

    DECLARE @Counter INT 

    DECLARE @SQL nvarchar(max) = N'SELECT @Counter = MAX(CAST(' + @cfield + ' as bigint)) from ' + @ctable 

    EXEC sp_executesql 
     @SQL 
    , N'@Counter int OUTPUT' 
    , @Counter = @Counter OUTPUT 

    SET ROWCOUNT @Counter 

    SELECT IDENTITY(INT, 1, 1) ID 
    INTO dbo.tally 
    FROM master.sys.all_columns c 
    CROSS JOIN master.sys.all_columns c1 

    SET ROWCOUNT 0 

    -- ADD (unique) clustered index 
    CREATE UNIQUE CLUSTERED INDEX PKC_Tally ON dbo.tally (ID) 
END 
2

表名不會喜歡這個工作.. 你可以使用EXEC使用它。

試試這個:

DECLARE @Counter INT; 

declare @strSql nvarchar(2000) 
set @strSql ='Select MAX(CAST('+ @cfield +' as bigint)) from' + @ctable 

exec sp_executesql @strSql,N'@Counter int output', @Counter output 
SELECT @Counter 

http://technet.microsoft.com/en-us/library/ms188332.aspx

+0

有沒有其他選項可以運行使用存儲過程? –

+0

這是另一個存儲過程嗎?... –

+0

Rolen ..它沒有工作..它給我不正確的語法靠近'+'。 –