sql set variable using COUNT

后端 未结 4 1776
陌清茗
陌清茗 2021-02-04 23:50

I am trying to make a simple query to my server and want the result to be stored in the variable @times.

DECLARE @times int

SET @times = SELECT COUNT(DidWin)as          


        
相关标签:
4条回答
  • 2021-02-05 00:05

    You can select directly into the variable rather than using set:

    DECLARE @times int
    
    SELECT @times = COUNT(DidWin)
    FROM thetable
    WHERE DidWin = 1 AND Playername='Me'
    

    If you need to set multiple variables you can do it from the same select (example a bit contrived):

    DECLARE @wins int, @losses int
    
    SELECT @wins = SUM(DidWin), @losses = SUM(DidLose)
    FROM thetable
    WHERE Playername='Me'
    

    If you are partial to using set, you can use parentheses:

    DECLARE @wins int, @losses int
    
    SET (@wins, @losses) = (SELECT SUM(DidWin), SUM(DidLose)
    FROM thetable
    WHERE Playername='Me');
    
    0 讨论(0)
  • 2021-02-05 00:10

    You just need parentheses around your select:

    SET @times = (SELECT COUNT(DidWin) FROM ...)
    

    Or you can do it like this:

    SELECT @times = COUNT(DidWin) FROM ...
    
    0 讨论(0)
  • 2021-02-05 00:17

    You want:

    DECLARE @times int
    
    SELECT @times =  COUNT(DidWin)
    FROM thetable
    WHERE DidWin = 1 AND Playername='Me'
    

    You also don't need the 'as' clause.

    0 讨论(0)
  • 2021-02-05 00:20

    You can use SELECT as lambacck said or add parentheses:

    SET @times = (SELECT COUNT(DidWin)as "I Win"
    FROM thetable
    WHERE DidWin = 1 AND Playername='Me');
    
    0 讨论(0)
提交回复
热议问题