因此,如果使用null项调用我的存储过程,我想将其设为''(否则它将不适用于我的结果列表) 如何做到这一点?
如果国家输入为美国,无效,无效,我希望我的代码能够吐出一个国家的人口,或者如果美国,纽约,纽约市投入,我希望我的代码更具特定人口。纽约市。
Create procedure [dbo].[GetPopulation]
@CountryCode varchar(3),
@State varchar(80)=null,
@City varchar(80)=null
as
if @State is Null
@State = ''
if @City is Null
@City = ''
select Population
FROM Countries
Where CountryCode = @CountryCode AND State = @State AND City=@City
答案 0 :(得分:4)
如果我是对的,你想在参数为空时忽略where子句
select Population
FROM Countries
Where (CountryCode = @CountryCode OR @CountryCode IS NULL)
AND (State = @State OR @State IS NULL)
AND (City=@City OR @City IS NULL)
如果您的问题是程序运行的应用程序参数,则默认参数为''
Create procedure [dbo].[GetPopulation]
@CountryCode varchar(3),
@State varchar(80)='',
@City varchar(80)=''
select Population
FROM Countries
Where CountryCode = @CountryCode AND State = @State AND City=@City
为美国或
运行dbo.GetPopulation 'US'
程序
dbo.GetPopulation 'US','New York', 'New York City' for New York City
答案 1 :(得分:0)
您无需将参数设为空:
SET ANSI_NULLS ON
Create procedure [dbo].[GetPopulation]
@CountryCode varchar(3),
@State varchar(80)=null,
@City varchar(80)=null
as
select Population
FROM Countries
Where CountryCode = @CountryCode AND
State = coalesce(@State, State) AND
City = coalesce(@City, City)
答案 2 :(得分:0)
答案 3 :(得分:0)
如果我理解你的问题 - 只需修复你的WHERE子句:
WHERE
CountryCode = @CountryCode
AND (State = @State OR @State is null)
AND (City = @City OR @City is null)
答案 4 :(得分:0)
@State varchar(80)= null - >这意味着“允许程序在没有@State参数的情况下运行” @State varchar(80)='' - >这意味着“如果在没有@State参数的情况下运行该过程,则将@State参数更改为''(空字符串)。
选项2的功能与此相同,因此您可以删除此部分:
if @State is Null
@State = ''
if @City is Null
@City = ''
唯一的另一件事是修复你的WHERE子句来处理缺少的参数值(当你在下面看到它时,希望这是不言自明的。)
那么这就是你的原始代码,修正了上面的解释:
Create procedure [dbo].[GetPopulation]
@CountryCode varchar(3),
@State varchar(80)='',
@City varchar(80)=''
as
select Population
FROM Countries
Where CountryCode = @CountryCode AND (State = @State OR @State = '') AND (City=@City OR @City = '')