Using the result of an [removed]e.g. Function call

2020-01-23 09:50发布

I am trying to write a stored procedure to assist with development of our database, but I am having some trouble using it. For example:

DECLARE @pID int;
SET @pID = 1;
EXEC WriteLog 'Component', 'Source', 'Could not find given id: ' + CAST(@pID AS varchar);

This yields the error (on SQL Server 2005):

Msg 102, Level 15, State 1, Line 4 Incorrect syntax near '+'.

Can someone explain to me why my syntax is incorrect, and the right way to solve this problem?

7条回答
看我几分像从前
2楼-- · 2020-01-23 10:32

Perhaps something like this?

DECLARE @pID int;
SET @pID = 1;

DECLARE @Message NVARCHAR(50);

SET @Message = 'Could not find given id: ' + CAST(@pID AS varchar)
EXEC WriteLog 'Component', 'Source', @Message;
查看更多
啃猪蹄的小仙女
3楼-- · 2020-01-23 10:33

You can't do operations on the parameters of a stored procedure. You should assign that value on another variable and then pass it to your SP.

DECLARE @pID int, @nameId VARCHAR(100);
SET @pID = 1;
SET @nameId = 'Could not find given id: ' + CAST(@pID AS varchar);

EXEC WriteLog 'Component', 'Source', @nameId
查看更多
等我变得足够好
4楼-- · 2020-01-23 10:35
DECLARE @pID int;
declare @IdAsString varchar(100)

SET @pID = 1;

Select @IdAsString ='Could not find given id: ' + Cast(@pId as varchar(10))

EXEC WriteLog 'Component', 'Source', @IdAsString

As pointed out by Martin, the following only applies to columns not variables.

Note that I have amended your cast to varchar(10) this will allow for integers larger than 1 digit. varchar will only allow 1 character

查看更多
做个烂人
5楼-- · 2020-01-23 10:38

DECLARE @id int

SET @id = 10

SELECT LTRIM(RTRIM(STR(@id))) AS stringValue

查看更多
倾城 Initia
6楼-- · 2020-01-23 10:49

Use this code to print a Sql Server Error message:

BEGIN TRY  
    -- Generate a divide-by-zero error.  
    SELECT 1/0;  
END TRY  
BEGIN CATCH  
    SELECT  
        ERROR_NUMBER() AS ErrorNumber  
        ,ERROR_SEVERITY() AS ErrorSeverity  
        ,ERROR_STATE() AS ErrorState  
        ,ERROR_PROCEDURE() AS ErrorProcedure  
        ,ERROR_LINE() AS ErrorLine  
        ,ERROR_MESSAGE() AS ErrorMessage;  
END CATCH;  
GO  

Here is the result set.

Copy
-----------

(0 row(s) affected)

ErrorNumber ErrorSeverity ErrorState  ErrorProcedure  ErrorLine  ErrorMessage
----------- ------------- ----------- --------------- ---------- ----------------------------------
8134        16            1           NULL            4          Divide by zero error encountered.

(1 row(s) affected)
查看更多
The star\"
7楼-- · 2020-01-23 10:55

Try this instead...

DECLARE @pID int;
SET @pID = 1;

DECLARE @message varchar(255);
SET @message = 'Could not find given id: ' + CAST(@pID AS varchar)

EXEC WriteLog 'Component', 'Source', @message;
查看更多
登录 后发表回答