SQL WHERE语句不起作用100%

时间:2011-01-07 07:53:52

标签: asp.net sql sql-server sql-server-2005

我希望返回全球 = 可见 = 以及中的值州 = 佛罗里达州,但这并未返回全球

的所有其他值
select  * from Table1
where (visible = 'yes' and State = 'Florida') or Worldwide= 'yes'
order by ID DESC

编辑:我的不好

对不起男/女,这句话确实有效!我在声明中选择了TOP 8 *,这就是为什么它没有返回所有记录!当我拿出TOP 8时,它起作用了!我的坏!

4 个答案:

答案 0 :(得分:2)

使用以下脚本,查询输出预期的内容。

创建数据

DECLARE @Table1 TABLE (
  ID INTEGER IDENTITY(1, 1)
  , State VARCHAR(32)
  , Visible VARCHAR(32)
  , WorldWide VARCHAR(32)
)

INSERT INTO @Table1
SELECT 'Florida', 'Yes', 'Yes'  
UNION ALL SELECT 'Florida', 'Yes', 'No'  
UNION ALL SELECT 'Florida', 'No', 'Yes'  
UNION ALL SELECT 'Florida', 'No', 'No'  
UNION ALL SELECT 'Other State', 'Yes', 'Yes'  
UNION ALL SELECT 'Other State', 'Yes', 'No'  
UNION ALL SELECT 'Other State', 'No', 'Yes'  
UNION ALL SELECT 'Other State', 'No', 'No'  

选择

SELECT  *
FROM    @Table1
WHERE   (Visible = 'Yes' AND State = 'Florida') OR WorldWide = 'Yes'

<强>输出

ID  State           Visible WorldWide
1   Florida          Yes    Yes
2   Florida          Yes    No
3   Florida          No     Yes
5   Other State      Yes    Yes
7   Other State      No     Yes

答案 1 :(得分:1)

试试这个:

where State = 'Florida' AND (visible = 'yes' or Worldwide= 'yes')

另一个涵盖所有可能语法的案例:

where UPPER([State]) LIKE '%FLORIDA%' AND 
((UPPER(visible) LIKE '%YES%') OR (UPPER(Worldwide) LIKE '%YES%'))

答案 2 :(得分:1)

也许你有一些空位可能会给你带来麻烦。

select  * from Table1
where (IsNull(visible,'') = 'yes' and IsNull(State,'') = 'Florida') 
or IsNull(Worldwide,'')= 'yes'
order by ID DESC

同时检查排序规则是否区分大小写。可以在服务器,数据库或列级别设置排序规则,因此您需要检查以下内容:

服务器整理

SELECT SERVERPROPERTY('COLLATION')

数据库整理

SELECT DATABASEPROPERTYEX('DATABASENAME', 'Collation') SQLCollation;

列整理

Select table_name, column_name, collation_name
From information_schema.columns
Where table_name = @table_name

答案 3 :(得分:1)

您最多有4个问题

  • 区分大小写
  • 空间
  • 空值
  • 意外数据

可以合并的变化

--case
(LOWER(visible) = 'yes' and LOWER(State) = 'Florida') or LOWER(Worldwide) = 'yes'

--spaces
(RTRIM(LTRIM(visible)) = 'yes' and RTRIM(LTRIM(State)) = 'Florida') or RTRIM(LTRIM(Worldwide)) = 'yes'

--nulls
(visible = 'yes' and State = 'Florida') or ISNULL(Worldwide, 'yes') = 'yes'

--unexpected data: need samples