2016-11-21 92 views
0

enter image description here創建表,並使用if語句

enter image description here

我有這個問題,我真的不明白

我需要幫助理解和回答在座它

+1

讓我先說這不是現實世界的情景,但我想他們試圖讓你應用不同的概念。你對這個問題的理解有什麼困難?簡而言之,他們要求您獲取RACES_COMPLETED在500到900之間的所有行,這是一條基本的SELECT語句。你對SQL Server有什麼經驗? – bassrek

+0

沒有太先進,但我理解得很好 –

+0

我認爲有人希望您使用SQL Server Management Studio將某些行選入臨時表中。打印消息需要另一個SQL語句。還有其他的可能性。 –

回答

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 
+1

非常感謝。非常感謝 –