Update a table from two comma separated parameter as input

自闭症网瘾萝莉.ら 提交于 2019-12-02 02:05:41

There is no built in function to parse these comma separated string. However, yo can use the XML function in SQL Server to do this. Something like:

DECLARE @sID VARCHAR(100) = '1,2,3,4';
DECLARE @sOrder VARCHAR(10) = '2,4,1,3';

DECLARE @sIDASXml xml = CONVERT(xml,
                            '<root><s>' + 
                            REPLACE(@sID, ',', '</s><s>') + 
                            '</s></root>');

DECLARE @sOrderASXml xml = CONVERT(xml,
                        '<root><s>' + 
                        REPLACE(@sOrder, ',', '</s><s>') + 
                        '</s></root>');

;WITH ParsedIDs
AS
(
    SELECT ID = T.c.value('.','varchar(20)'),
    ROW_NUMBER() OVER(ORDER BY (SELECT 1)) AS RowNumber
    FROM @sIDASXml.nodes('/root/s') T(c)
), ParsedOrders
AS
(
    SELECT "Order" = T.c.value('.','varchar(20)'),
        ROW_NUMBER() OVER(ORDER BY (SELECT 1)) AS RowNumber
    FROM @sOrderASXml.nodes('/root/s') T(c)
)
UPDATE t
SET t."Order" = p."Order"
FROM @tableName AS t
INNER JOIN
(
   SELECT i.ID, p."Order"
   FROM ParsedOrders p 
   INNER JOIN ParsedIDs i ON p.RowNumber = i.RowNumber
) AS p ON t.ID = p.ID;

Live Demo

Then you can put this inside a stored procedure or whatever.

Note that: You didn't need to do all of this manually, it should be some way to make this gridview update the underlying data table automatically through data binding. You should search for something like this instead of all this pain.

SWeko

You could use a table valued parameter to avoid sending delimiter-separated values or even XML to the database. To do this you need to:

  1. Declare a parameter type in the database, like this:

    CREATE TYPE UpdateOrderType TABLE (ID int, Order int)
    
  2. After that you can define the procedure to use the parameter as

    CREATE PROCEDURE UpdateOrder (@UpdateOrderValues UpdateOrderType readonly)
    AS
    BEGIN
      UPDATE t
        SET OrderID = tvp.Order
        FROM <YourTable> t
          INNER JOIN @UpdateOrderValues tvp ON t.ID=tvp.ID
    END
    

    As you can see, the SQL is trivial compared to parsing XML or delimited strings.

  3. Use the parameter from C#:

    using (SqlCommand command = connection.CreateCommand()) {
      command.CommandText = "dbo.UpdateOrder";
      command.CommandType = CommandType.StoredProcedure;
    
      //create a table from your gridview data
      DataTable paramValue = CreateDataTable(orderedData) 
      SqlParameter parameter = command.Parameters
                                .AddWithValue("@UpdateOrderValues", paramValue );
      parameter.SqlDbType = SqlDbType.Structured;
      parameter.TypeName = "dbo.UpdateOrderType";
    
      command.ExecuteNonQuery();
    }
    

    where CreateDataTable is something like:

    //assuming the source data has ID and Order properties
    private static DataTable CreateDataTable(IEnumerable<OrderData> source) {
      DataTable table = new DataTable();
      table.Columns.Add("ID", typeof(int));
      table.Columns.Add("Order", typeof(int));
      foreach (OrderData data in source) {
          table.Rows.Add(data.ID, data.Order);
      }
      return table;
    }
    

    (code lifted from this question)

As you can see this approach (specific to SQL-Server 2008 and up) makes it easier and more formal to pass in structured data as a parameter to a procedure. What's more, you're working with type safety all the way, so much of the parsing errors that tend to crop up in string/xml manipulation are not an issue.

You can use charindex like

DECLARE @id VARCHAR(MAX)
DECLARE @order VARCHAR(MAX)

SET @id='1,2,3,4,'
SET @order='2,4,1,3,'

WHILE CHARINDEX(',',@id) > 0
BEGIN
DECLARE @tmpid VARCHAR(50)
SET @tmpid=SUBSTRING(@id,1,(charindex(',',@id)-1))
DECLARE @tmporder VARCHAR(50)
SET @tmporder=SUBSTRING(@order,1,(charindex(',',@order)-1))

UPDATE dbo.Test SET
[Order]=@tmporder
WHERE ID=convert(int,@tmpid)

SET @id = SUBSTRING(@id,charindex(',',@id)+1,len(@id))
SET @order=SUBSTRING(@order,charindex(',',@order)+1,len(@order))
END
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!