简体   繁体   中英

SQL Server - Update table and return the Updated rows

I have a SQL Server database which has a lot of information inside.

I want to select top 50 rows in a single query (which I did, with no problem) but then I want to update a column from false to true, so next time I select I wont select the same, my code looks like this:

string Command = "UPDATE HubCommands SET [Alreadytaken] = 'true' FROM (SELECT TOP 50 [CommandId],[DeviceId],[Commandtext], [HashCommand],[UserId]  FROM HubCommands) I WHERE [HubId] = '18353fe9-82fd-4ac2-a078-51c199d9072b'";

using (SqlConnection myConnection = new SqlConnection(SqlConnection))
{
    using (SqlDataAdapter myDataAdapter = new SqlDataAdapter(Command, myConnection))
    {
        DataTable dtResult = new DataTable();

        myDataAdapter.Fill(dtResult);

        foreach (DataRow row in dtResult.Rows)
        {
            Guid CommandId, DeviceId, UserId;
            Guid.TryParse(row["CommandId"].ToString(), out CommandId);
            Guid.TryParse(row["DeviceId"].ToString(), out DeviceId);
            Guid.TryParse(row["UserId"].ToString(), out UserId);

            Console.WriteLine("CommandId" + CommandId);
        }
    }
}

This code does work, and it updates what I ask it to update, but I don't get nothing in the data table, its like it is always updating but not selecting.

If I do a normal select it does work and give information.

Does anyone have any idea how to update and get some data back, in a single query?

So your question is:

How can I update a table in SQL Server using C# and return the truly updated rows as a DataTable ?

First You have multiple issues in your query.

You should use 1 and 0 , not true or false. SQL-Server has a bit datatype and not a Boolean .

Second , this is how you should've constructed your query:

DECLARE @IDs TABLE
(
    [CommandId] uniqueidentifier
);

INSERT INTO @IDs
SELECT [CommandId] FROM HubCommands
WHERE [HubId] = '18353fe9-82fd-4ac2-a078-51c199d9072b' AND [Alreadytaken] = 0;

UPDATE HubCommands 
SET [Alreadytaken] = 1
WHERE CommandId IN
(
    SELECT [CommandId] FROM @IDs
);

SELECT * FROM HubCommands 
WHERE CommandId IN
(
    SELECT [CommandId] FROM @IDs 
);

Wrap all the above in a single string and use SqlDataReader . No need for an Adapter in you case (Since we're mixing commands unlike what the adapter usually does):

var sqlCommand = new SqlCommand(Command, myConnection);
SqlDataReader dataReader = sqlCommand.ExecuteReader();

DataTable dtResult = new DataTable();
dtResult.Load(dataReader);

I highly advise you to create a stored procedure accepting HubId as a parameter that does all the above work. It is neater and better for maintenance.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM