我在下面的存儲過程中寫了這個,並得到不正確的語句。用於計數動態表項的MS SQL存儲過程
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 [email protected]
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 [email protected]
--DEALLOCATE PREPARE get_counter; -- removing the statement from the memory.
Return @Counter;
END
它運行良好,但我不能在櫃檯得到的結果,請人幫我(我知道,我還沒有分配任何價值的櫃檯,但如果我做我得到錯誤)。
你的答案馬丁後,我不得不現在你代替我的代碼的:
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
我猜我遲到了:) – 2012-07-21 13:28:57
優秀的@Martin Smith。你能解釋一下EXEC的代碼嗎? – user1542653 2012-07-21 13:50:57
我想我從這http://msdn.microsoft.com/en-us/library/ms175170%28v=sql.105%29.aspx – user1542653 2012-07-21 15:13:20