日期:2014-05-17  浏览次数:20595 次

SQL where like in
兄弟姐妹们,

有个问题,请教下,在SQL中如下数据Table,
Code Name
201412 ABC
203413 BCD
201333 CDE
203244 DEF
209416 FEG
207417 EGH
205418 GHI
202419 HIJ
202420 IJK
301412 JKL
303413 FZD
301333 EFH
403244 WTY
509416 GYU
507417 YTJ
605418 EGP
602419 DGU
602420 QRE
我只用三个变量
declare  @Code1 as nvarchar(20)
declare  @Code2 as nvarchar(20)
declare  @code3 as nvarchar(20)

我想实现,如果
情况1,中间任意一个变量填写值,那么就以这个为条件过滤
set @Code1 = 20
set @Code2 = ''
set @Code3 = ''
那将所有code中包含20

情况2,中间任意两个变量填写值,那么出现
set @Code1 = '20'
set @Code2 = '30'
set @Code3 = ''
那将所有code中包含20和30的数据

情况3,如果我的变量如下填写
set @Code1 = '201333'
set @Code2 = '203244'
set @Code3 = '40'
希望得到的结果是包含201333,203244和40的所有数据


情况4,都不填写值
set @Code1 = ''
set @Code2 = ''
set @Code3 = ''
所有数据都出来

请问SQL这个Where条件怎么写?
------解决方案--------------------
----------------------------------------------------------------
-- Author  :DBA_Huangzj(發糞塗牆)
-- Date    :2013-10-25 11:31:09
-- Version:
--      Microsoft SQL Server 2012 (SP1) - 11.0.3128.0 (X64) 
-- Dec 28 2012 20:23:12 
-- Copyright (c) Microsoft Corporation
-- Enterprise Edition (64-bit) on Windows NT 6.2 <X64> (Build 9200: )
--
----------------------------------------------------------------
--> 测试数据:[table]
if object_id('[table]') is not null drop table [table]
go 
create table [table]([Code] int,[Name] varchar(3))
insert [table]
select 201412,'ABC' union all
select 203413,'BCD' union all
select 201333,'CDE' union all
select 203244,'DEF' union all
select 209416,'FEG' union all
select 207417,'EGH' union all
select 205418,'GHI' union all
select 202419,'HIJ' union all
select 202420,'IJK' union all
select 301412,'JKL' union all
select 303413,'FZD' union all
select 301333,'EFH' union all
select 403244,'WTY' union all
select 509416,'GYU' union all
select 507417,'YTJ' union all
select 605418,'EGP' union all
select 602419,'DGU' union all
select 602420,'QRE'
--------------开始查询--------------------------
declare  @Code1 as nvarchar(20)=null
declare  @Code2 as nvarchar(20)=null
declare  @code3 as nvarchar(20)=NULL
DECLARE @sql VARCHAR(max)

SET @sql='
select * from [table]'
--IF @Code1 IS NOT NULL
--BEGIN
-- SET @sql=@sql+'where code like '+'''%'+@code1+'%'''
--END 
 IF  @code2 is NOT NULL  AND @code1 is NOT NULL AND @code3 IS NOT NULL 
begin 
SET @sql=@sql+'where code like '+'''%'+@code1+'%'''&