I had wrote this below stored procedure and getting incorrect statement.
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
Then I had wrote another one:
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
It is running fine but I can’t get the result in the Counter , anyone please help me(I know that I haven’t assigned any value to the counter but if I do I get error).
After your answer martin I had replace my code with yours now its :
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
Now I had retrieved it .
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
You should use
SYSNAMEfor object identifiers andQuotenamerather than concatenating the square brackets yourself.