c#SQL存储过程Id问题

时间:2016-03-15 11:07:08

标签: c# sql bulk

我的存储过程不像我想的那样工作,无法弄清楚如何解决它。使用SQL Server management studio 2008

这是存储值的地方:

SELECT *
  FROM [Events].[dbo].[Fouten] where TreinId = 1338

然而,'1338'是Treinen表中一个字段的名称,该字段与TreinId链接到Fouten表。例如:TreinId = 136,Name ='1338'

所以我试图插入名称字段并从另一个表中检索Id,以便我可以得到我的结果:

SELECT *
      FROM [Events].[dbo].[Fouten] where TreinId = 136

存储过程(microsoft sql manager 2008):

USE [Events]
GO
/****** Object:  StoredProcedure [dbo].[sp_BatchInsert]    Script Date: 03/15/2016 11:58:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[sp_BatchInsert] (@Datum date, @Foutcode varchar(8), @Omschrijving varchar(50), @Module varchar(20), @Time time(3), @Teller int, @Mnemo varchar(9), @treinNaam varchar(10))
AS
BEGIN
            INSERT INTO dbo.Fouten (Datum,FoutCode,Omschrijving,Module,Time,Teller,Mnemo,TreinId) VALUES (@Datum,@Foutcode,@Omschrijving,@Module,@Time,@Teller,@Mnemo,(SELECT TreinId from [Events].[dbo].[Treinen] WHERE Name = @treinNaam));
END 

enter image description here

c#c​​ode:

public void BatchBulkCopy(string rapport)
        {
            // Get the DataTable 
            DataTable dtInsertRows = TextReader(rapport);

            using (SqlBulkCopy sbc = new SqlBulkCopy(GetConnectionString(), SqlBulkCopyOptions.CheckConstraints))
            {
                sbc.DestinationTableName = "dbo.Fouten";
                sbc.BatchSize = 8000;


                sbc.ColumnMappings.Add("Datum", "Datum");
                sbc.ColumnMappings.Add("Foutcode", "FoutCode");
                sbc.ColumnMappings.Add("Omschrijving", "Omschrijving");
                sbc.ColumnMappings.Add("Module", "Module");
                sbc.ColumnMappings.Add("Time", "Time");
                sbc.ColumnMappings.Add("Teller", "Teller");
                sbc.ColumnMappings.Add("Mnemo", "Mnemo");
                sbc.ColumnMappings.Add("treinNaam", "TreinId");

                sbc.NotifyAfter = dtInsertRows.Rows.Count;
                sbc.SqlRowsCopied += new SqlRowsCopiedEventHandler(sbc_SqlRowsCopied);

                try
                {
                    sbc.WriteToServer(dtInsertRows);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message.ToString());
                }
                sbc.Close();
            }

        }

1 个答案:

答案 0 :(得分:0)

您应该能够SELECT提供INSERT语句,而不是尝试强制使用VALUES语法:

INSERT INTO dbo.Fouten 
(Datum,FoutCode,Omschrijving,Module,Time,Teller,Mnemo,TreinId)
SELECT
    @Datum,
    @Foutcode,
    @Omschrijving,
    @Module,
    @Time,
    @Teller,
    @Mnemo,
    TreinId from [Events].[dbo].[Treinen]
WHERE
    Name = @treinNaam;

如果您的RDBMS具有检索表的最新插入的自动增量数的功能,那么它就变得更加容易。