【问题标题】:Truncate table then insert data into same table only inserts 1 record截断表然后将数据插入同一个表只插入1条记录
【发布时间】:2013-01-06 13:02:53
【问题描述】:

有谁知道我在这里做错了什么,我有一个从远程源获取货币数据的网页,我获取数据并通过存储过程将其插入到 sql 数据库中。如果我将截断放在插入语句的前面,它会截断表并插入最后一条记录。 如果我删除截断,它会插入所有记录。

truncate table tblTablename;

insert into tblTablename
(columns)
values
(data)

上面将插入289条记录中的最后一条记录。

如果我删除截断,则插入所有 289 条记录。

我曾尝试使用 waitfor 1 秒钟,但也无法正常工作。

我不知道还能做什么,所以任何帮助将不胜感激

在网页中我有一个 foreach 循环

乔治

/---------- SQL代码-----

  ALTER PROCEDURE [dbo].[atSP_InsertCurrency]
-- Add the parameters for the stored procedure here
@CurrencyCountry VarChar(150),
@CurrencyRate VarChar(150),
@UpdateSuccessFail  INT OUTPUT 
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
TRUNCATE TABLE [dbo].[at_CurrencyRates];

WAITFOR DELAY '000:00:01'


INSERT INTO [dbo].[at_CurrencyRates]
(
    [CurrencyCode],
    [CurrencyExchangeRate]
)
VALUES
(
    @CurrencyCountry,
    @CurrencyRate
)
IF(@@ROWCOUNT > 0)
    BEGIN
    select  @UpdateSuccessFail = '1'
    END
    ELSE
    BEGIN
    select  @UpdateSuccessFail = '0'
    END
END

【问题讨论】:

  • 请发布您的实际代码。 insert into tblTablename (columns) values (data) 只插入 1 行,除非您有多个项目用逗号分隔。
  • 您这里显示的代码添加了一条记录,而不是289。您可以发布添加289记录的代码!
  • 或者你可能调用你的存储过程 289 次?

标签: sql-server sql-server-2008 tsql stored-procedures


【解决方案1】:

如果您调用它 289 次以逐行插入,则需要将 TRUNCATE TABLE [dbo].[at_CurrencyRates]; 移出存储过程。

每次调用存储过程时,它都会从表中删除所有行,因此您最终只会得到刚刚插入的一行。

更好的办法是更改存储过程以一次性插入所有需要的行,而不是一次插入一个。您可以使用表值参数来传递所有所需的行,然后您只需要 TRUNCATE 后跟 INSERT [dbo].[at_CurrencyRates] ... SELECT * FROM @TVP

【讨论】:

  • 嗨,马克,谢谢,我想我可以做一个如果存在并更新货币汇率,如果他们添加新货币,插入它。或者在网页中创建另一个函数,首先截断表格然后插入记录。
  • 嗨,Martin,谢谢,现在只是在阅读表值参数,直到今天才听说过。
  • @CareerChange - If you are using C# then example here。这也演示了MERGE 语法
【解决方案2】:

我想我会为任何检索 json 数据然后想要使用 MERGE

将数据批量插入 sql 的访问者添加我的工作源代码

我不是专业的编码员,我是在被裁员后自己学习的,我必须承认我学的越多,我知道的越少,下面的代码来自花费数小时谷歌搜索 merge昨天和阅读其他人的博客/帖子,这里提到了许多网站,但感谢所有这些编码人员放弃他们的时间和博客,介绍他们如何通过提示和技巧解决问题。

我提供的代码在我的项目中运行良好。

 string dbConn = ConfigurationManager.ConnectionStrings["CurrDB"].ConnectionString;
const string strCurrencyCode = "http://SomeRemoteJsonSource.com"; 

public void InsertCurrency()
        {

        WebClient wc = new WebClient();
        var dict = JsonConvert.DeserializeObject<Dictionary<string, string>>(wc.DownloadString(strCurrencyCode));

        string tmpTable = "create table #at_CurrencyCountries (CurrencyCountry varchar(150), CurrencyCountryCode varchar(4))";

        DataTable table = new DataTable();
        table.Columns.Add(new DataColumn("CurrencyCountry", typeof(string)));
        table.Columns.Add(new DataColumn("CurrencyCountryCode", typeof(string)));

        foreach (var wy in dict.AsEnumerable())
            {
            DataRow row = table.NewRow();
            row["CurrencyCountry"] = wy.Value;
            row["CurrencyCountryCode"] = wy.Key;
            table.Rows.Add(row);
            }

        using (SqlConnection cn = new SqlConnection(dbConn))
            {
            cn.Open();
            SqlCommand cmd = new SqlCommand(tmpTable, cn);
            cmd.ExecuteNonQuery();

            using (SqlBulkCopy bulk = new SqlBulkCopy(cn))
                {
                bulk.DestinationTableName = "#at_CurrencyCountries";
                bulk.WriteToServer(table);
                }
            string mergeSql = "merge into at_CurrencyCountries as Target "
                + "using #at_CurrencyCountries as Source "
                + "on "
                + "Target.CurrencyCountry=Source.CurrencyCountry "
                + "and "
    + "Target.CurrencyCountryCode = Source.CurrencyCountryCode "
                + "when matched then "
                + "update set Target.CurrencyCountryCode=Source.CurrencyCountryCode "
                + "when not matched then "
                + "insert (CurrencyCountry,CurrencyCountryCode) values (Source.CurrencyCountry, Source.CurrencyCountryCode)"
                + "WHEN NOT MATCHED BY SOURCE THEN DELETE;";
            cmd.CommandText = mergeSql;
            cmd.ExecuteNonQuery();               
            cmd.CommandText = "drop table #at_CurrencyCountries";
            cmd.ExecuteNonQuery();
            }
        }

乔治

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-17
    • 1970-01-01
    相关资源
    最近更新 更多