创建表并使用if语句

时间:2016-11-21 18:30:32

标签: sql-server sql-server-2012

enter image description here

enter image description here

我有这个我不太懂的问题

我需要帮助理解或回答

1 个答案:

答案 0 :(得分:1)

--Create the table on the fly with the condition stated
SELECT
    TEAM_NAME,
    RACES_COMPETED
INTO [TOP TEAMS] 
FROM YourTable
WHERE RACES_COMPETED >= 500 and RACES_COMPETED <= 900


--Store the number of teams in the new table in a variable for ease of use
DECLARE @topTeams INT
SET @topTeams = (SELECT COUNT(*) FROM [TOP TEAMS])


--If there are teams in the table, print the number of teams. If there aren't any, print the other statment
IF @topTeams > 0
    BEGIN
        SELECT 'NO. OF TOP TEAMS: ' + CAST(@topTeams AS VARCHAR)
    END
ELSE
    BEGIN
        SELECT 'NO TOP TEAMS EXIST'
    END

这是使用TEMP TALBE的相同代码

--Drop the TEMP TABLE if it exists
IF OBJECT_ID('tempdb..#TOP_TEAMS') IS NOT NULL DROP TABLE #TOP_TEAMS

--Create the table on the fly with the condition stated
SELECT
    TEAM_NAME,
    RACES_COMPETED
INTO #TOP_TEAMS
FROM YourTable
WHERE RACES_COMPETED >= 500 and RACES_COMPETED <= 900


--Store the number of teams in the new table in a variable for ease of use
DECLARE @topTeams INT
SET @topTeams = (SELECT COUNT(*) FROM #TOP_TEAMS)


--If there are teams in the table, print the number of teams. If there aren't any, print the other statment
IF @topTeams > 0
    BEGIN
        SELECT 'NO. OF TOP TEAMS: ' + CAST(@topTeams AS VARCHAR)
    END
ELSE
    BEGIN
        SELECT 'NO TOP TEAMS EXIST'
    END