声明变量

时间:2011-09-07 00:35:22

标签: sql-server variables

我有一个包含2列ID(标识),errormessage(10种可能的错误消息)

的表

现在我有一些业务逻辑,我可以从中获取可能的错误消息(如果有的话)。 我有10个SP。我想要column2 =错误消息中的所有错误消息。

根据我使用的逻辑,它只更新最后更新的错误(不是全部) 让我们说业务逻辑1(通过执行sp1)ID = 1我得到errorMsg = <Data Invalid> 对于ID = 1,执行SP2,我得到<Data Corrupted>

现在,我想在一列中获取这两条消息。 我知道它很难解释(因为我有10个SP)请帮助我使用我应该使用的方法。

PS:我已经为SP中的每个错误消息声明了一个变量,并在其中添加了下一条消息,但即使该错误没有发生,也显示错误。例如:

declare @errormessage1 varchar(20)
set @errormessage1 = <Data Invalid>  

declare @errormessage2 varchar(20)
set @errormessage2 = <Data corrupted>

update my_table
set errormessage= @errormessage1 + @errormessage2
from my_table

即使errormessage1没有无效数据,它仍然显示在col2 = +中 现在,这里的问题是它应该只显示实际错误(所有声明的错误)

谢谢

1 个答案:

答案 0 :(得分:0)

在我们等待更多细节时,我们会有一些猜测

-- Create a local table variables to hold processing results
DECLARE @PROCESSING_RESULTS
(
   -- size and type these accurately
   id int NOT NULL
,  error_message varchar(8000)
)
DECLARE @ID int
,  @error_message varchar(8000)

-- Load up the table 
-- Not sure what the signature of the proc looks like so guessing here
-- Either use an insert into with the execute
-- This assumes an invocation of the proc returns a result set 
INSERT INTO
    @PROCESSING_RESULTS
EXECUTE dbo.SP1 @id = 1


-- This approach assumes output parameters
EXECUTE dbo.SP1 @id = 1, @error_message output
INSERT INTO
    @PROCESSING_RESULTS
([id], error_message)
SELECT 1, @error_message

-- Repeat the above approach for all 10 procs

-- At this point, all the errors are in our processing_results table
-- so we should do something with them.
-- Assuming you want a CSV list of all the error messages, this will
-- mash all the results 
SELECT STUFF(
 (SELECT ',' + PR.error_message
FROM @PROCESSING_RESULTS PR
ORDER BY PR.error_message
FOR XML PATH('')),1,1,'') AS CSV
相关问题