如何根据参数更改在一个select语句中获取数据?

时间:2017-08-25 07:26:11

标签: sql sql-server

我有一张这样的表:

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

例如,我声明:

declare @name varchar(10)

set @name = 'abc'

我需要获取姓氏等于@name's姓氏的所有姓名。如果@name为null,则获取所有记录。 IN ONE SELECT STATEMENT

4 个答案:

答案 0 :(得分:0)

在列姓氏上的同一个表上进行内部联接

SELECT *
FROM   table t1
INNER JOIN table t2 ON t1.surname = t2.surname 
WHERE  t1.name = COALESCE(@name, t1.name)

答案 1 :(得分:0)

SELECT t1.*
FROM table t1
WHERE (ISNULL(@name,0) != 0 AND t1.surname = @name) OR (ISNULL(@name,0)=0)

答案 2 :(得分: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)

答案 3 :(得分:0)

我认为你可以使用它:

foreach key $arrayA_order {
    puts $key
    puts $arrayA($key)
}

示例数据

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)    
{    
    Label YourControl= (Label)e.Row.FindControl("YourControl");    
    if (YourControl != null)    
    {    
        if (YourControl.Text.Trim() == "0")    
        {    
            LinkButton YourControl= (LinkButton)e.Row.FindControl("YourControl");    
            YourControl.Visible = false;    
        }

    }

}

输出名称= NULL:

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

输出名称='abc':

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