我的存储过程存在一些问题。
我正在尝试对照我的表GOTWVotes
进行查找,如果VotedBy
在将表决结果写入表之前尚未进行表决(这是可行的),但是如果VotedBy
之前已经进行了表决不要写到表中并返回VoteCount
为1。
尽管VotedBy
存在时它不会写到表中,VoteCount
的值总是看起来为0
任何帮助将不胜感激
CREATE PROCEDURE [dbo].[Votes]
@VotedMember BIGINT,
@VotedBy BIGINT
AS
DECLARE @votecount INT
BEGIN TRY
BEGIN TRANSACTION t_Transaction
SELECT TOP 1 * FROM [GOTWVotes] WITH (TABLOCKX)
SELECT @votecount = COUNT(*) FROM [dbo].[GOTWVotes]
WHERE [VotedBy] = @VotedBy
IF @votecount = 0
INSERT INTO
[dbo].[GOTWVotes] ([VotedMember],[VotedBy])
VALUES
(@VotedMember, @VotedBy)
COMMIT TRANSACTION t_Transaction
END TRY
BEGIN CATCH
SET @votecount = -1
ROLLBACK TRANSACTION t_Transaction
END CATCH
RETURN @votecount
答案 0 :(得分:0)
您可以执行以下代码
struct foo_type_b
要调用上述存储过程,您需要编写以下代码
CREATE PROCEDURE [dbo].[Votes]
@VotedMember BIGINT,
@VotedBy BIGINT,
@votecount INT OUTPUT
AS
BEGIN TRY
BEGIN TRANSACTION t_Transaction
SET @votecount = 0
IF NOT EXISTS(SELECT 1 FROM [dbo].[GOTWVotes]
WHERE [VotedBy] = @VotedBy)
BEGIN
INSERT INTO
[dbo].[GOTWVotes] ([VotedMember],[VotedBy])
VALUES
(@VotedMember, @VotedBy)
END
ELSE
BEGIN
SELECT @votecount = COUNT(*) FROM [dbo].[GOTWVotes]
WHERE [VotedBy] = @VotedBy
END
COMMIT TRANSACTION t_Transaction
END TRY
BEGIN CATCH
SET @votecount = -1
ROLLBACK TRANSACTION t_Transaction
END CATCH
答案 1 :(得分:0)
这似乎太复杂了。我在想这样的事情:
CREATE PROCEDURE [dbo].[Votes] (
@VotedMember BIGINT,
@VotedBy BIGINT,
@retval int output
)
BEGIN
INSERT INTO dbo.GOTWVotes (VotedMember, VotedBy)
SELECT v.VotedMember, v.VotedBy
FROM (VALUES (@VotedMember, @VotedBy)) v(VotedMember, VotedBy)
WHERE NOT EXISTS (SELECT 1
FROM dbo.GOTWVotes gwv
WHERE gwv.VotedBy = v.VotedBy
);
SET @retval = @@ROWCOUNT;
END;
我怀疑您想要做的事情也可能受到约束。