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
4

2 回答 2

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

于 2013-10-16T03:37:02.160 回答
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
于 2013-10-16T07:05:23.080 回答