我正在一个应用程序中,用户通过单击与每行关联的复选框选择gridview中的某些行,并且在选定的行中,只应在数据库中更新一个值。 我正在使用以下查询
update Items
set bitIsTab = 1
where ReqID = 3
假设用户从gridview中选择了4个值,我必须将这4行bitIsTab设置为1.如何通过调用查询一次来更新这些行,或者我必须调用相同的查询次数与所选记录的数量相同
答案 0 :(得分:7)
如果你知道ReqID
你能做什么
update Items
set bitIsTab = 1
where ReqID in (1,2,3,4)
答案 1 :(得分:5)
好的查询应如下所示,更新项目1,2,3,4:
UPDATE Items
SET bitIsTab = 1
WHERE ReqID IN (1,2,3,4);
然而,可以使用Linq
:
List<int> selectedIds = { 1, 2, 3, 4 };
var itemsToBeUpdated = (from i in yourContext.Items
where selectedIds.Contains(i.ReqID)
select i);
itemsToBeUpdated.ForEach(i=>i.bitIsTab = 1);
yourContext.SubmitChanges();
或者您可以在存储过程中使用VARCHAR
:
CREATE PROCEDURE sp_setTabItems
@ids varchar(500) AS
UPDATE Items
SET bitIsTab = 1
WHERE charindex(',' + ReqID + ',', ',' + @ids + ',') > 0;
然后使用“1,2,3,4”作为存储过程参数。
执行存储过程:
EXEC sp_setTabItems '1,2,3,4'
也可以使用bitIsTab
作为参数,以更可重复使用的方式完成:
CREATE PROCEDURE sp_setTabItems
@isTab bit,
@ids varchar(500) AS
UPDATE Items
SET bitIsTab = @isTab
WHERE charindex(',' + ReqID + ',', ',' + @ids + ',') > 0;
以这种方式执行:
EXEC sp_setTabItems '1,2,3,4',1
我更新了存储过程解决方案,因为将INT
与VARCHAR
进行比较将无法与EXEC
一起使用。
答案 2 :(得分:1)
一个简单的解决方案是
DECLARE @id varchar(30)
SET @id = '1,3,2'
UPDATE [Items]
SET bitIsTab = 0
WHERE ReqID IN (
SELECT s
FROM dbo.Split(',', @id)
)
,其中
CREATE FUNCTION dbo.Split (@sep char(1), @s varchar(512))
RETURNS table
AS
RETURN (
WITH Pieces(pn, start, stop) AS (
SELECT 1, 1, CHARINDEX(@sep, @s)
UNION ALL
SELECT pn + 1, stop + 1, CHARINDEX(@sep, @s, stop + 1)
FROM Pieces
WHERE stop > 0
)
SELECT pn,
SUBSTRING(@s, start, CASE WHEN stop > 0 THEN stop-start ELSE 512 END) AS s
FROM Pieces
)
答案 3 :(得分:0)
如果你必须将数据作为分离的ID列表传递,那么你需要为how to split and insert CSV data into a new table in single statement?编写一个函数
CREATE PROCEDURE sp_setTabItems
@ids varchar(500) -- 1,2,4,6
AS
UPDATE Items
SET bitIsTab = 1
WHERE ReqID IN (Select Part From dbo.inline_split_me(@ids)
这是函数
CREATE FUNCTION inline_split_me (@SplitOn char(1),@String varchar(7998))
RETURNS TABLE AS
RETURN (WITH SplitSting AS
(SELECT
LEFT(@String,CHARINDEX(@SplitOn,@String)-1) AS Part
,RIGHT(@String,LEN(@String)-CHARINDEX(@SplitOn,@String)) AS Remainder
WHERE @String IS NOT NULL AND CHARINDEX(@SplitOn,@String)>0
UNION ALL
SELECT
LEFT(Remainder,CHARINDEX(@SplitOn,Remainder)-1)
,RIGHT(Remainder,LEN(Remainder)-CHARINDEX(@SplitOn,Remainder))
FROM SplitSting
WHERE Remainder IS NOT NULL AND CHARINDEX(@SplitOn,Remainder)>0
UNION ALL
SELECT
Remainder,null
FROM SplitSting
WHERE Remainder IS NOT NULL AND CHARINDEX(@SplitOn,Remainder)=0
)
SELECT Part FROM SplitSting
)