我在存储过程下面写了这个并且得到了不正确的语句。
ALTER PROCEDURE dbo.[Counter]
@TableName VARCHAR(100)
AS
BEGIN
DECLARE @Counter INT
DECLARE @SQLQ VARCHAR(200)
SET NOCOUNT ON;
--SET @TableName = 'Member';
SET @SQLQ = 'SELECT COUNT(*) FROM dbo.[' + @TableName + ']';
--Preparing the above sql syntax into a new statement(get_counter).
--Getting an error here I had googled the prepare statement but don't know why facing this error.
PREPARE get_counter FROM @SQLQ;
@Counter = EXEC get_counter; -- here @resutl gets the value of the count.@TableName
DEALLOCATE PREPARE get_counter; -- removing the statement from the memory.
END
然后我又写了一篇:
ALTER PROCEDURE dbo.[Counter]
@TableName VARCHAR(100)
AS
BEGIN
DECLARE @Counter INT
DECLARE @SQLQ VARCHAR(200)
SET NOCOUNT ON;
--SET @TableName = 'Member';
SET @SQLQ = 'SELECT COUNT(*) FROM dbo.[' + @TableName + ']';
--Preparing the above sql syntax into a new statement(get_counter).
Execute @SQLQ; -- here @resutl gets the value of the count.@TableName
--DEALLOCATE PREPARE get_counter; -- removing the statement from the memory.
Return @Counter;
END
它运行良好,但我无法在 Counter 中得到结果,请任何人帮助我(我知道我没有为计数器分配任何值,但如果我这样做了,我会得到错误)。
在你回答马丁之后,我现在用你的代码替换了我的代码:
ALTER PROCEDURE dbo.[Counter] @SchemaName SYSNAME = 'dbo' , @TableName SYSNAME
AS
BEGIN
SET NOCOUNT ON;
DECLARE @SQLQ NVARCHAR(1000)
DECLARE @Counter INT;
SET @SQLQ = 'SELECT @Counter = COUNT(*) FROM ' +
Quotename(@SchemaName) + '.' + Quotename(@TableName);
EXEC sp_executesql
@SQLQ ,
N'@Counter INT OUTPUT',
@Counter = @Counter OUTPUT
Return SELECT @Counter
END
现在我已经找回了它。
ALTER PROCEDURE dbo.[CreateBusinessCode]
@MemberID bigint,
@len int,
@RewardAccountID bigint,
@ConnectionStatusID tinyint,
@Assign smalldatetime
AS
BEGIN
SET NOCOUNT ON;
DECLARE @counter INT
EXEC @counter = dbo.Counter 'dbo','member';
Select @counter;
END