2017-09-13 78 views
0

我一直在编写这个存储过程,而我对存储过程是一种新的东西。我一直试图把插入到循环,但逻辑是不正确的。存储过程只从临时表中插入一条记录

基本上,下面的存储过程只将最后一行插入表中。 但是,当我打印出临时表时,它会正确显示所有数据,但不知何故插入/更新无法正常工作

下面是存储过程的脚本。谁能告诉我,我在这里错过了什么?

--exec [dbo].[spAddIntoTemplateCalculationsTable] @templateID=1,@parameterList='0:C:Test:True:0,0:B:TEST2:False:0,0:A-b/c*a::False:0', 
[email protected] = 'test' 

ALTER PROCEDURE [dbo].[spAddIntoTemplateCalculationsTable] 
( -- Add the parameters for the stored procedure here 
@templateID nvarchar(max), 
@parameterList nvarchar(max), 
@EmployeeNo nvarchar(16) 
)  
AS 
BEGIN 


Declare @ErrorNo integer = '', 

@ErrorMessage nvarchar(max) = '', 
@SPName nvarchar(max) = '' 

DECLARE @paramID nvarchar(MAX),@formula nvarchar(MAX), @property nvarchar(MAX),@samplesRequired nvarchar(MAX),@tUnitOfMeasures_id int, 
@Pos int,@strSampleData nvarchar(MAX),@IntCounter int,@test int 

     DECLARE @tmpParameterParam table 
      (
       paramID nvarchar(MAX), 
        formula nvarchar(MAX), 
        property nvarchar(MAX), 
        samplesRequired nvarchar(MAX), 
        tUnitOfMeasures_id int 

       ) 


     SET @parameterList = LTRIM(RTRIM (@parameterList))+ ',' 
     SET @Pos = CHARINDEX (',', @parameterList,1) 
     --SET @IntCounter = 1 
      IF REPLACE(@parameterList, ',' , '') <> '' 
        begin 
         WHILE @Pos > 0 
         BEGIN 
           SET @strSampleData = LTRIM(RTRIM(LEFT(@parameterList, @Pos -1))) 
           IF @strSampleData <> '' 

           BEGIN 

            set @paramID = substring(@strSampleData,0, CHARINDEX(':',@strSampleData,0)) 
            --Remove the substring and move the string to the next token(column) 
            set @strSampleData = substring(@strSampleData, LEN(@paramID)+2, LEN(@strSampleData)) 

            set @formula = substring(@strSampleData,0, CHARINDEX(':',@strSampleData,0)) 
            --Remove the substring and move the string to the next token(column) 
            set @strSampleData = substring(@strSampleData, LEN(@formula)+2, LEN(@strSampleData)) 

            --update tSpecScaleValidation set LastTriggeredTime=getdate() where id= @tSpecScaleValidation_id 

            set @property = substring(@strSampleData,0, CHARINDEX(':',@strSampleData,0)) 
            set @strSampleData = substring(@strSampleData, LEN(@property)+2, LEN(@strSampleData)) 

            set @samplesRequired = substring(@strSampleData,0, CHARINDEX(':',@strSampleData,0)) 
            set @strSampleData = substring(@strSampleData, LEN(@samplesRequired)+4, LEN(@strSampleData))   


            set @tUnitOfMeasures_id = substring(@strSampleData,0, CHARINDEX(':',@strSampleData,0)) 
            --to get the last token from the string(column) 
            set @tUnitOfMeasures_id = substring(@strSampleData, LEN(@tUnitOfMeasures_id)+1, LEN(@strSampleData)) 



            insert into @tmpParameterParam 
            --select @IntCounter,@strSampleData 
            select @paramID,@formula,@property,@samplesRequired,@tUnitOfMeasures_id 


           END 
           SET @parameterList = RIGHT(@parameterList, LEN (@parameterList) - @Pos) 
           set @Pos = CHARINDEX(',', @parameterList,1) 
           SET @IntCounter = @IntCounter + 1 
         END 
        END 

        begin transaction t1 


        begin try 
         declare @setno int 
         select * from @tmpParameterParam 
         --begin 
          if EXISTS (SELECT * FROM tTemplate_Calculation where id = @paramID) 
           update tTemplate_Calculation 
           set [email protected], 
           property = @property , 
           [email protected], 
           [email protected]_id 
           where id = @paramID 
          else 
           insert into tTemplate_Calculation 
           select @templateID,@formula,@property,@samplesRequired,@tUnitOfMeasures_id,@EmployeeNo,getdate() 
           FROM @tmpParameterParam 

         --end 
         commit transaction t1 

        end try 

     Begin Catch 
      Select 
        @ErrorMessage = ERROR_MESSAGE(), 
        @SPName = ERROR_PROCEDURE(), 
        @ErrorMessage = ERROR_MESSAGE(); 

      rollback transaction t1 

      select @ErrorMessage 
     End Catch 

END 
+0

我试图插入和更新基于临时表的记录。但它只是插入最后一行 –

+0

也,我有一个检查,如果paramID为0,它应该插入,否则,更新表 –

+0

这将失败,当表是空的转换nvarchar值时转换失败'错误? “当用exec [dbo]执行时,数据类型位和任何内容都不会被插入[spAddIntoTemplateCalculationsTable] @ templateID = 1,@ parameterList ='0:C:Test:True:0,0:B:TEST2:Fals e:0, 0:Ab/c * a :: False:0',@EmployeeNo ='test',显示的3行是过程中的调试选择语句。 –

回答

0

请尝试以下操作。我已经在我的Sql服务器中成功执行了它。

ALTER PROCEDURE [dbo].[spAddIntoTemplateCalculationsTable] 
(
    -- Add the parameters for the stored procedure here 
    @templateID NVARCHAR(MAX), 
    @parameterList NVARCHAR(MAX), 
    @EmployeeNo NVARCHAR(16) 
) 
AS 
BEGIN 


    DECLARE @ErrorNo INTEGER, 
     @ErrorMessage NVARCHAR(MAX), 
     @SPName NVARCHAR(MAX) 

    DECLARE @paramID NVARCHAR(MAX), 
     @formula NVARCHAR(MAX), 
     @property NVARCHAR(MAX), 
     @samplesRequired NVARCHAR(MAX), 
     @tUnitOfMeasures_id INT, 
     @Pos INT, 
     @strSampleData NVARCHAR(MAX), 
     @IntCounter INT, 
     @test INT 

    DECLARE @tmpParameterParam TABLE 
(
    paramID NVARCHAR(MAX), 
    formula NVARCHAR(MAX), 
    property NVARCHAR(MAX), 
    samplesRequired NVARCHAR(MAX), 
    tUnitOfMeasures_id INT 
) 


    SET @parameterList = LTRIM(RTRIM(@parameterList)) + ',' 
    SET @Pos = CHARINDEX(',', @parameterList, 1) 
     --SET @IntCounter = 1 
    IF REPLACE(@parameterList, ',', '') <> '' 
     BEGIN 
      WHILE @Pos > 0 
       BEGIN 
        SET @strSampleData = LTRIM(RTRIM(LEFT(@parameterList, @Pos - 1))) 
        IF @strSampleData <> '' 
         BEGIN 

          SET @paramID = SUBSTRING(@strSampleData, 0, CHARINDEX(':', @strSampleData, 0)) 
            --Remove the substring and move the string to the next token(column) 
          SET @strSampleData = SUBSTRING(@strSampleData, LEN(@paramID) + 2, LEN(@strSampleData)) 

          SET @formula = SUBSTRING(@strSampleData, 0, CHARINDEX(':', @strSampleData, 0)) 
            --Remove the substring and move the string to the next token(column) 
          SET @strSampleData = SUBSTRING(@strSampleData, LEN(@formula) + 2, LEN(@strSampleData)) 

            --update tSpecScaleValidation set LastTriggeredTime=getdate() where id= @tSpecScaleValidation_id 

          SET @property = SUBSTRING(@strSampleData, 0, CHARINDEX(':', @strSampleData, 0)) 
          SET @strSampleData = SUBSTRING(@strSampleData, LEN(@property) + 2, LEN(@strSampleData)) 

          SET @samplesRequired = SUBSTRING(@strSampleData, 0, CHARINDEX(':', @strSampleData, 0)) 
          SET @strSampleData = SUBSTRING(@strSampleData, LEN(@samplesRequired) + 4, LEN(@strSampleData))   


          SET @tUnitOfMeasures_id = SUBSTRING(@strSampleData, 0, CHARINDEX(':', @strSampleData, 0)) 
            --to get the last token from the string(column) 
          SET @tUnitOfMeasures_id = SUBSTRING(@strSampleData, LEN(@tUnitOfMeasures_id) + 1, LEN(@strSampleData)) 



          INSERT INTO @tmpParameterParam 
            --select @IntCounter,@strSampleData 
            SELECT @paramID, @formula, @property, @samplesRequired, @tUnitOfMeasures_id 


         END 
        SET @parameterList = RIGHT(@parameterList, LEN(@parameterList) - @Pos) 
        SET @Pos = CHARINDEX(',', @parameterList, 1) 
        SET @IntCounter = @IntCounter + 1 
       END 
     END 

    BEGIN TRANSACTION t1 


    BEGIN TRY 
     DECLARE @setno INT 
     SELECT * 
     FROM @tmpParameterParam 
         --begin 
     IF EXISTS (SELECT * 
        FROM tTemplate_Calculation 
        WHERE id = @paramID) 
      UPDATE tTemplate_Calculation 
      SET  formula = @formula, property = @property, samplesRequired = @samplesRequired, tUnitOfMeasures_id = @tUnitOfMeasures_id 
      WHERE id = @paramID 
     ELSE 
      INSERT INTO tTemplate_Calculation 
        SELECT @templateID, @formula, @property, @samplesRequired, @tUnitOfMeasures_id, @EmployeeNo, GETDATE() 
        FROM @tmpParameterParam 

         --end 
     COMMIT TRANSACTION t1 

    END TRY 

    BEGIN CATCH 
     SELECT @ErrorMessage = ERROR_MESSAGE(), @SPName = ERROR_PROCEDURE(), @ErrorMessage = ERROR_MESSAGE() ; 

     ROLLBACK TRANSACTION t1 

     SELECT @ErrorMessage 


    END CATCH 

END 
+0

感谢@Rajan,但它仍然从临时表中插入最后一行3次。 –

+0

你可以给我一个SQL来生成表“tTemplate_Calculation”,并给我一个参数列表来执行SP – Rajan

+0

GO /******对象:表[dbo]。[tTemplate_Calculation]脚本日期:9/13/2017下午2点43分55秒******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [DBO]。[tTemplate_Calculation]( \t [ID] [INT] IDENTITY(1,1)NOT NULL, \t [tTemplate_id] [INT] NULL, \t [配方] [nvarchar的](10)NULL, \t [属性] [为nvarchar(50)NULL, \t [samplesRequired] [比特] NULL, \t [tUnitOfMeasures_id] [INT] NULL, \t [为employeeno] [nvarchar的](50)NULL, \t [dateTimeStamps] [日期时间] NULL )ON [PRIMARY] GO –

0

我不认为你是那么遥远。我的理解是,你希望在tTemplate_Calculation中每个paramid有1行,所以我会更改表格定义 ,以便paramid是唯一的,但不是标识类型。

CREATE TABLE [dbo].[tTemplate_Calculation]( 
[id] [int] unique, --IDENTITY(1,1) NOT NULL, 
[tTemplate_id] [int] NULL, 
[formula] [nvarchar](10) NULL, 
[property] [nvarchar](50) NULL, 
[samplesRequired] [bit] NULL, 
[tUnitOfMeasures_id] [int] NULL, 
[employeeNo] [nvarchar](50) NULL, 
[dateTimeStamps] [datetime] NULL) 

,修改SP包括在表变量标识列,当你来到更新/插入阶段使用@i和@j变量使用胶印创建一个循环,并获取从表中数据传递变回声明的变量

alter PROCEDURE [dbo].[spAddIntoTemplateCalculationsTable] 
( -- Add the parameters for the stored procedure here 
@templateID nvarchar(max),@parameterList nvarchar(max),@EmployeeNo nvarchar(16))  
AS 
BEGIN 
Declare @ErrorNo integer = '', 
@ErrorMessage nvarchar(max) = '', 
@SPName nvarchar(max) = '', 
@i int , 
@j int 
DECLARE @paramID nvarchar(MAX),@formula nvarchar(MAX), @property nvarchar(MAX),@samplesRequired nvarchar(MAX),@tUnitOfMeasures_id int, 
@Pos int,@strSampleData nvarchar(MAX),@IntCounter int,@test int 
DECLARE @tmpParameterParam table (id int identity , paramID nvarchar(MAX), formula nvarchar(MAX), property nvarchar(MAX), samplesRequired nvarchar(MAX),tUnitOfMeasures_id int) 
set @i = 0 
set @j = 0 
     SET @parameterList = LTRIM(RTRIM (@parameterList))+ ',' 
     SET @Pos = CHARINDEX (',', @parameterList,1) 
     --SET @IntCounter = 1 
      IF REPLACE(@parameterList, ',' , '') <> '' 
        begin 
         WHILE @Pos > 0 
         BEGIN 
           SET @strSampleData = LTRIM(RTRIM(LEFT(@parameterList, @Pos -1))) 
           IF @strSampleData <> '' 

           BEGIN 

            set @paramID = substring(@strSampleData,0, CHARINDEX(':',@strSampleData,0)) 
            --Remove the substring and move the string to the next token(column) 
            set @strSampleData = substring(@strSampleData, LEN(@paramID)+2, LEN(@strSampleData)) 

            set @formula = substring(@strSampleData,0, CHARINDEX(':',@strSampleData,0)) 
            --Remove the substring and move the string to the next token(column) 
            set @strSampleData = substring(@strSampleData, LEN(@formula)+2, LEN(@strSampleData)) 

            --update tSpecScaleValidation set LastTriggeredTime=getdate() where id= @tSpecScaleValidation_id 

            set @property = substring(@strSampleData,0, CHARINDEX(':',@strSampleData,0)) 
            set @strSampleData = substring(@strSampleData, LEN(@property)+2, LEN(@strSampleData)) 

            set @samplesRequired = substring(@strSampleData,0, CHARINDEX(':',@strSampleData,0)) 
            set @strSampleData = substring(@strSampleData, LEN(@samplesRequired)+4, LEN(@strSampleData))   

            set @tUnitOfMeasures_id = substring(@strSampleData,0, CHARINDEX(':',@strSampleData,0)) 
            --to get the last token from the string(column) 
            set @tUnitOfMeasures_id = substring(@strSampleData, LEN(@tUnitOfMeasures_id)+1, LEN(@strSampleData)) 

            insert into @tmpParameterParam 
            --select @IntCounter,@strSampleData 
            select @paramID,@formula,@property,@samplesRequired,@tUnitOfMeasures_id 

           END 
           SET @parameterList = RIGHT(@parameterList, LEN (@parameterList) - @Pos) 
           set @Pos = CHARINDEX(',', @parameterList,1) 
           SET @IntCounter = @IntCounter + 1 
           set @i = @i + 1 
         END 
        END 
        select @i as intcounter 
        begin transaction t1 
        begin try 
         declare @setno int 

         while @j < @i 
         begin 
           select @paramID = t.paramID , 
            @formula = t.formula, 
            @property = t.property, 
            @samplesRequired = t.samplesRequired, 
            @tUnitOfMeasures_id = t.tUnitOfMeasures_id 
           from @tmpParameterParam t 
           order by t.id offset @i rows fetch next 1 rows only 

          if EXISTS (SELECT * FROM tTemplate_Calculation where id = @paramid) 
           begin 
           select 'updating' , @i, @j 
           update tTemplate_Calculation 
           set formula= @formula, 
           property = @property , 
           [email protected], 
           [email protected]_id 

           end 
          else 
           begin 
           select 'inserting' , @i, @j 
           insert into tTemplate_Calculation 
           ( [id], 
            [tTemplate_id] , 
            [formula] , 
            [property], 
            [samplesRequired], 
            [tUnitOfMeasures_id] , 
            [employeeNo] , 
            [dateTimeStamps]) 

           select @paramid, @templateID,@formula,@property,@samplesRequired,@tUnitOfMeasures_id,@EmployeeNo,getdate() 
           end 
          set @j [email protected] + 1 
         end 
         commit transaction t1 
        end try 
     Begin Catch 
      Select 
        @ErrorMessage = ERROR_MESSAGE(), 
        @SPName = ERROR_PROCEDURE(), 
        @ErrorMessage = ERROR_MESSAGE(); 
      rollback transaction t1 
      select @ErrorMessage 
     End Catch 

END 

当SP被称为

set nocount on 
truncate table tTemplate_Calculation 

exec [dbo].[spAddIntoTemplateCalculationsTable] @templateID=1,@parameterList='0:C:Test:0:0,0:B:TEST2:1:0,0:A-b/c*a::0:0', @EmployeeNo = 'test' 
select * from tTemplate_Calculation 

这是结果

intcounter 
----------- 
3 


--------- ----------- ----------- 
inserting 3   0 


-------- ----------- ----------- 
updating 3   1 


-------- ----------- ----------- 
updating 3   2 

id   tTemplate_id formula property           samplesRequired tUnitOfMeasures_id employeeNo           dateTimeStamps 
----------- ------------ ---------- -------------------------------------------------- --------------- ------------------ -------------------------------------------------- ----------------------- 
0   1   A-b/c*a              0    0     test            2017-09-13 13:05:12.310 
+0

嘿,我现在明白了。谢谢@P.Salmon –