存储过程仅从临时表中插入一条记录

时间:2017-09-13 05:11:00

标签: sql-server stored-procedures

我一直在编写这个存储过程,而且我对Stored Procedures不熟悉。我一直试图将插入放入循环中,但逻辑不对。

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

以下是存储过程的脚本。谁能告诉我,我在这里想念的是什么?

--exec [dbo].[spAddIntoTemplateCalculationsTable] @templateID=1,@parameterList='0:C:Test:True:0,0:B:TEST2:False:0,0:A-b/c*a::False:0',
--@EmployeeNo = '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 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

2 个答案:

答案 0 :(得分:0)

请尝试以下操作。我在我的Sql server中成功执行了它。

<ListView x:Name="lvDataBinding" HorizontalContentAlignment="Stretch" BorderThickness="0" Margin="10" Grid.Row="3" Background="{x:Null}" ItemsSource="{Binding}" Foreground="White">
    <ListView.ItemTemplate>
        <DataTemplate DataType="{x:Type local:CL_Operation}">
            <Border BorderBrush="White" BorderThickness="0" CornerRadius="3" Margin="0,3" Grid.ColumnSpan="4" Background="Transparent">
                <Border.Effect>
                    <DropShadowEffect BlurRadius="5" ShadowDepth="5" />
                </Border.Effect>
                <Grid Background="Transparent" Margin="0,1">
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition />
                        <ColumnDefinition />
                        <ColumnDefinition Width="1.5*"/>
                        <ColumnDefinition />
                    </Grid.ColumnDefinitions>
                    <Grid.RowDefinitions>
                        <RowDefinition Height="60"/>
                    </Grid.RowDefinitions>
                    <StackPanel Orientation="Vertical" Margin="50,5" >
                        <!-- <TextBlock Text="Customer" Foreground="#33B6EF" FontSize="20" />-->
                        <TextBlock Text="{Binding strPriorite}" FontSize="20" />
                    </StackPanel>
                    <StackPanel Orientation="Vertical" Grid.Column="1">
                        <!-- <TextBlock Text="Location" Foreground="#33B6EF" FontSize="20" />-->
                        <TextBlock Text="{Binding strRetardAvanceText}" FontSize="20" />
                    </StackPanel>
                    <StackPanel Orientation="Vertical" Grid.Column="2">
                        <!-- <TextBlock Text="Created On" Foreground="#33B6EF" FontSize="20" />-->
                        <TextBlock Text="{Binding strNoOfOp}" FontSize="20" />
                    </StackPanel>
                    <StackPanel Orientation="Vertical" Grid.Column="3">
                        <!-- <TextBlock Text="Quantity" Foreground="#33B6EF" FontSize="20" /> -->
                        <TextBlock Text="{Binding strDescriptionOp}" FontSize="20" />
                    </StackPanel>
                </Grid>
            </Border>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>


<Window.Resources>
    <DataTemplate DataType="{x:Type local:CL_Operation}" >
        <Border BorderThickness = "1" BorderBrush = "Green" Margin = "2" Padding = "5" Width = "900" CornerRadius = "3" >
            <Grid >
                <Grid.ColumnDefinitions >
                    <ColumnDefinition />
                    <ColumnDefinition />
                    <ColumnDefinition />
                </Grid.ColumnDefinitions >
                <TextBlock Grid.Column = "0" Text = "{Binding Path = strRetardAvanceText}" Background = "LightBlue" />
                <!-- <TextBlock Grid.Column = "0" Text = "{Binding Path = strNoOfOp}" Background = "LightBlue" />-->
                <TextBlock Grid.Column = "1" Text = "{Binding Path = strDescriptionOp}" Background = "LightBlue" />
                <TextBlock Grid.Column = "2" Text = "{Binding Path = strNoArticle}" FontStyle = "Italic" />
            </Grid >
        </Border >
        <DataTemplate.Triggers >
            <DataTrigger Binding = "{Binding Path = strRetardAvanceText}" Value = "26 jrs" >
                <Setter Property = "ListBoxItem.Foreground" Value = "Red" ></Setter >
            </DataTrigger >
        </DataTemplate.Triggers >
    </DataTemplate >
</Window.Resources >
<Grid >
    <ListBox x:Name = "listBox1" ItemsSource = "{Binding}" />
</Grid >

答案 1 :(得分:0)

我不认为你那么遥远。我的理解是你想在tTemplate_Calculation中每个参数有一行,所以我会改变表的定义 因此,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变量创建一个循环,使用offset和fetch将数据从表变量传递回到声明的变量

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 , 
                                samplesRequired=@samplesRequired, 
                                tUnitOfMeasures_id=@tUnitOfMeasures_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 =@j + 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