有人能告诉我这个存储过程有什么问题吗?我只是新手并尝试创建一个新的存储过程,我已声明@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 :(得分: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
答案 1 :(得分: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