截断表然后将数据插入到同一个表中只插入1条记录

时间:2013-01-06 13:02:54

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

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

truncate table tblTablename;

insert into tblTablename
(columns)
values
(data)

以上内容将插入289条记录中的最后一条记录。

如果我删除truncate,则插入所有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

2 个答案:

答案 0 :(得分:2)

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

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

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

答案 1 :(得分:1)

我想我会为任何检索json数据的访问者添加我的工作源代码,然后想要使用 MERGE

将数据批量插入到sql中

我不是一名专业的程序员,我在被裁员后学习自己,我必须承认我学的越多,我知道的越少,下面的代码就是花费数小时用谷歌搜索合并昨天和阅读其他人的博客/帖子,到这里提到的许多网站,但感谢所有那些编写者放弃他们的时间和博客关于他们如何用提示和技巧解决问题。

我提供的代码在我的项目中可以正常工作。

 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();
            }
        }

乔治