2019年10月7日 星期一

Set variables in stored procedure using EXECUTE sp_executesql

While this doesn't need to be dynamic SQL:
ALTER PROCEDURE [dbo].[selectRecords]
  @psID INT
AS
BEGIN
  SET NOCOUNT ON; 

  DECLARE @rc INT;

  SELECT @rc = COUNT(Name) 
    FROM dbo.Asset_Log
    WHERE ID = @psID;
END
GO
I'll assume there is other logic here that you haven't shared that makes it a necessity. If that is the case:
ALTER PROCEDURE [dbo].[selectRecords]
  @psID INT
AS
BEGIN
  SET NOCOUNT ON; 

  DECLARE 
    @rc     INT = 0,
    @sql    NVARCHAR(1000),
    @params NVARCHAR(1000);

  SET @params = N'@psID INT, @rc INT OUTPUT';

  SET @sql = N'SELECT @rc = COUNT(Name)
    FROM dbo.Asset_Log
    WHERE ID = @psID;';

  EXEC sp_executesql @sql, @params, @psID, @rc OUTPUT;
END
GO

from : https://stackoverflow.com/questions/11507413/set-variables-in-stored-procedure-using-execute-sp-executesql

沒有留言:

張貼留言