我有一个名为favorite_question的列,它被更新如下:
if it is null
then insert a value
if not null then old value + , + new value
if((select Favorite_question from User_Details where User_Id = @userid) IS NULL)
begin
update User_Details
set Favorite_question = (cast(@questionid as varchar(50)))
where User_Id = @userid
end
else
begin
update User_Details
set Favorite_question = ((select Favorite_question
from User_Details
where User_Id = @userid ) + ',' +
(cast(@questionid as varchar(50))))
where User_Id = @userid
end其中,@userid是用户价值,@questionid是问题价值
varchar(50)取favorite_question
我想从该列中随机删除一个值
例如。
如果列值为=2、6、8、9、5,并且我想从其中删除8或从上面删除任何值
同样的sql查询是什么?
发布于 2012-03-03 22:01:43
UPDATE语句可以优化很多。整个"if((select ...“可以替换为:
UPDATE User_Details
SET Favorite_question = COALESCE(Favorite_question + ',', '') +
cast(@questionid as varchar(50))
where User_Id = @userid现在来看您真正的问题:如何从Favorite_questions列中删除文本(数字)。假设该列包含值'2,6,8,9,5‘。如果你想删除2,你得到的是',6,8,9,5',所以必须添加处理逻辑来删除开头的孤立逗号。如果你想删除5,你得到的是'2,6,8,9,',所以必须添加处理逻辑来删除末尾的孤立逗号。如果你想删除8,你得到的是'2,6,,9,5',所以你必须添加处理逻辑来删除中间的一个双逗号。如果列包含值'12,6,8,29,5,2‘,而您想要删除'2',那么您不希望以'1,6,8,9,5’结束。
基本上,我们应该花费大量的精力来从文本中删除正确的数字,并使文本处于干净的状态(no ',6,8 ,9,5‘,'2,6,9,5’或诸如此类)。SQL在文本处理方面不是很好。
最基本的问题是你的数据模型没有标准化。您应该从User_Details表中删除列Favorite_question,并创建一个额外的表User_FavoriteQuestions (User_Id,Question_id)来为您的用户存储FavoriteQuestions。然后,您的第一个UPDATE语句将替换为
INSERT INTO User_FavoriteQuestions (User_Id, Question_id)
VALUES(@userid, @questionid)你真正的问题变成了:
DELETE FROM User_FavoriteQuestions
WHERE User_Id = @userid AND Question_id = @questionid一旦你规范化了你的数据模型,用SQL操作它就变得容易多了。
https://stackoverflow.com/questions/9546434
复制相似问题