在一个select语句中,如何使用其姓氏获取特定名称?

时间:2017-08-24 15:28:06

标签: sql sql-server

例如,

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

这是我的表:

| name     |   surname   |
|----------|-------------|
| John     |  Black      |
| John     |  Reese      |
| Kevin    |  Love       |
| Lionel   |  Messi      |

我需要获取 John Black !如果name是john,则检查一个Select查询中的lastname。否则取其他人。谢谢!

对不起,我无法澄清自己。让我再试一次。

首先,我的变量是'John'。如果name是john,我想获取名称为John的记录,但同时我想将这些姓氏更新为'BLACK'

4 个答案:

答案 0 :(得分:0)

您可以使用Sandwich

order by

这可以完成单个查询中的所有逻辑。

答案 1 :(得分:0)

为什么不包含姓氏的第二个参数?

您可以使用 private IEnumerable<string> GetBindingPropertyNames(DependencyObject target) { return from path in GetBindingPaths(target) select path.Split('.').First(); } private IEnumerable<string> GetBindingPaths(DependencyObject target) { var ret = new List<string>(); LocalValueEnumerator lve = target.GetLocalValueEnumerator(); while (lve.MoveNext()) { LocalValueEntry entry = lve.Current; if (entry.Value is DependencyObject) { ret.AddRange(GetBindingPaths(entry.Value as DependencyObject)); } if (BindingOperations.IsDataBound(target, entry.Property)) { Binding binding = (entry.Value as BindingExpression).ParentBinding; ret.Add(binding.Path.Path); } } return ret; } 方法确定姓氏是空还是空。如果它不为空,它将返回与姓氏和名字相匹配的所有记录。如果surname为null,它将返回与forename('john')

匹配的所有记录
coalesce()

<强>更新

从您的最新更新中,您只是想使用所返回的第一条记录的姓氏更新所有带有forename'john'的记录的姓氏。

DECLARE @forename VARCHAR(10)
SET @forename = 'John'

DECLARE @surname VARCHAR(10) = NULL

SELECT       t.*
FROM         yourTable t
WHERE        t.forename = @forename
AND          (t.surname = COALESCE(@surname, t.surname) OR @surname IS NULL)    

答案 2 :(得分:0)

SELECT * FROM fooTable 

{{1}}

我认为这是OP的要求,但我不确定。

供参考: How do I UPDATE from a SELECT in SQL Server?

答案 3 :(得分:0)

以下两种解决方案可为您提供所需的结果。第二个使用纯SQL来获取返回集,而第一个使用T-SQL和SQL的组合。

create   procedure [dbo].[getName] @name varchar(100), @surname varchar(100)
as
begin

declare @l_found smallint;

select @l_found = count(*) 
  from nameTable 
 where name    = @name 
   and surname = @surname;
print 'found: ' + cast(@l_found as varchar)

if @l_found = 0  
   select * 
     from nameTable 
    where name = @name;
else 
   select * 
     from nameTable 
    where 
     name = @name 
      and surname = @surname;

end;

<强>替代

alter   procedure [dbo].[getName] @name varchar(100), @surname varchar(100)
as
begin

with foundit as ( select count(*) c 
                    from nameTable 
                   where name    = @name 
                     and surname = @surname )
select * 
  from nameTable 
 where name    = @name 
   and surname = @surname
union all
select * from nameTable
where name = @name 
  and 0    = (select c from foundit);
end;