2017-08-25 65 views
-7

我有一個表是這樣的:如何根據參數更改獲取一條select語句中的數據?

---------- 
name | surname 
---------- 
abc | def 
----------- 
xxx | def 
---------- 
yyy | def 
---------- 
Comy | Xardas 
---------- 

例如,我宣佈:

declare @name varchar(10) 

set @name = 'abc' 

我需要獲取其姓氏等於@name's姓所有名稱。如果@name爲空,則獲取所有記錄。 IN ONE SELECT語句

回答

0

做一個內部在同一個表連接在列姓

SELECT * 
FROM table t1 
INNER JOIN table t2 ON t1.surname = t2.surname 
WHERE t1.name = COALESCE(@name, t1.name) 
0
SELECT t1.* 
FROM table t1 
WHERE (ISNULL(@name,0) != 0 AND t1.surname = @name) OR (ISNULL(@name,0)=0) 
0
DECLARE @MyTable TABLE (name varchar(20), surname varchar(20)) 
INSERT INTO @MyTable VALUES ('abc','def'),('xxx','def'),('yyy','def'), ('Comy','Xardas') 

declare @name varchar(10) 
set @name = 'abc' 

SELECT T.* FROM 
@MyTable T 
LEFT JOIN @MyTable T1 ON T.surname = T1.surname AND @name IS NOT NULL 
WHERE (T.name = @name or @name IS NULL) 
+0

當@name被定義爲空,所有行變爲零。 –

+0

如果你設置@ name = null,那麼你將得到@MyTable的所有行 –

0

我認爲你可以這樣做:

declare @name varchar(10) 
set @name = 'abc' 
SELECT * 
FROM YT T1 
WHERE EXISTS (SELECT 1 FROM YT T2 WHERE [email protected] AND T1.SURNAME=T2.SURNAME) OR @name IS NULL 

的樣本數據

CREATE TABLE YT (name varchar(20), surname varchar(20)); 
INSERT INTO YT VALUES ('abc','def'),('xxx','def'),('yyy','def'), ('Comy','Xardas'); 

室內用輸出名= NULL:

name surname 
abc def 
xxx def 
yyy def 
Comy Xardas 

輸出與名稱= 'ABC':

name surname 
abc def 
xxx def 
yyy def 
相關問題