gpt4 book ai didi

sql - 用于计算动态表项的 MS SQL 存储过程

转载 作者:行者123 更新时间:2023-12-04 05:38:35 25 4
gpt4 key购买 nike

我在存储过程下面写了这个,得到了不正确的语句。

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

最佳答案

您应该使用 SYSNAME用于对象标识符和 Quotename而不是自己连接方括号。

ALTER PROCEDURE dbo.[Counter] @TableName  SYSNAME,
@SchemaName SYSNAME = 'dbo'
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

SELECT @Counter
END

关于sql - 用于计算动态表项的 MS SQL 存储过程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11592327/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com