基于传递的参数对SQL表执行更新

时间:2012-10-10 14:19:20

标签: c# sql sqlcommand

这个程序已经编写完了,我需要在其中添加一个更新SQL语句来更新基于@IN的另一个表。在声明SQL命令后如何让它执行,我可以使用与其他sql命令相同的SQLConnection吗?这个程序做的是它在一个文件中解析一个名为个体的列表,从那里我只想更新SQL中的字段。第一个SQL已写入似乎正确执行现在我需要执行UpdtHasInv SQL并实际获取执行更新的代码是我需要帮助的地方。

到目前为止我所拥有的:

 static void InsertCustomData(Collection<Individuals> individuals)
    {
        #region
        string insertsql = "";

        insertsql = @"Insert into IND (IND_ID, ITEM_NAME,   INDL_ITEM_VALUE, XPTIM)
                        select  IND_ID, '{0}' as Item, '{1}' as val, (current timestamp -      curtime)"
                        FROM    IND 
                        where   IN = @IN";

    // this is SQL I added for update
          **UpdtHasInv = @"UPDATE Ind
                       SET    HAS_I = -1
                       WHERE  IN = @IN";**

        #endregion

        using (DB2Connection conn = DB2Helper.getConnection())
        {
            DB2Command cmd = conn.CreateCommand();                
            cmd.CommandTimeout = 600;
            cmd.Parameters.Add("@IN", "");

            if (conn.State == ConnectionState.Closed)
            {
                conn.Open();
            }

            foreach (Individuals individual in individuals)
            {
                cmd.Parameters["@IN"].Value = individual.In;


                foreach (CustomData customData in individual.CustomData)
                {
                    cmd.CommandText = string.Format(insertIndsql,   customData.Data.Key,            customData.Data.Value);  

我可以写一下:'cmd.CommandText = UpdtIsInv;'在这些界限之后:

 foreach (Individuals individual in individuals)
            {
                cmd.Parameters["@IN"].Value = individual.in

1 个答案:

答案 0 :(得分:0)

您只需使用分号在UPDATE之后附加INSERT即可。

insertIndsql = @"
INSERT INTO IND (IND_ID, ITEM_NAME,   INDL_ITEM_VALUE, XPTIMESTAMP)
SELECT  INDIVIDUAL_ID, '{0}' as Item, '{1}' as val, (current timestamp - curtime)
FROM    IND 
WHERE   TIN = @TIN;

UPDATE DB2INST1.Individual
SET    HAS_INVESTMENT = -1
WHERE  TIN = @TIN;";

执行时,两个语句将作为同一命令的一部分执行。