英文:
How to fetch a result of an int column data type from a table and if no record found select 0 as default in microsoft sql azure
问题
如何从表中获取整数列数据的结果,如果没有记录,则选择0作为默认值在Microsoft SQL Azure中。
我尝试过ISNULL,但它不起作用。
如果有一个名为student的表。
列名 数据类型
roll_nbr int
name varchar(30)
从student表中选择ISNULL(roll_nbr, 0) where name = 'Sam',我期望查询返回表中的roll_nbr(如果存在),否则如果没有找到行,则返回0作为默认值。
英文:
How to fetch a result of an int column data type from a table and if no record found select 0 as default in microsoft sql azure
I had tried ISNULL but it does not work.
In case there is a table named student.
Column_Name data_type
roll_nbr int
name varchar(30)
Select ISNULL(roll_nbr,0) FROM student where name = 'Sam;
I am expecting the query to return roll_nbr from the table if exists else return 0 as default if no rows is found.
答案1
得分: 2
使用COALESCE()
SELECT COALESCE((SELECT Roll_nbr FROM student WHERE NAME = 'Sam'), 0);
子查询将返回满足where
条件的RollNumber,否则将返回空白/空结果。在子查询上使用COALESCE
函数将返回第一个非空值。
使用ISNULL()
SELECT ISNULL((SELECT Roll_nbr FROM student WHERE NAME = 'Sam'), 0)
可以使用ISNULL()替代COALESCE()。
ISNULL函数只接受2个参数,用于替换空值,它是T-SQL函数。
COALESCE函数基于ANSI SQL标准,并接受1至n个参数,它返回第一个非空值。
英文:
You can modify your Azure Sql Query as below
Using COALESCE()
SELECT COALESCE((SELECT Roll_nbr FROM student WHERE NAME = 'Sam'), 0);
(http://sqlfiddle.com/#!18/9a6eaf/2)
The subquery will return the RollNumber if satisfies the where
condition else it will return blank/null result. Use of COALESCE
function on subquery will return first not null value.
Using ISNULL()
SELECT ISNULL((SELECT Roll_nbr FROM student WHERE NAME = 'Sam'), 0)
http://sqlfiddle.com/#!18/9a6eaf/6
> Instead of COALESCE() ISNULL() can be used.
> ISNULL function accepts only 2 arguments, used to replace null value and it is T-SQL function.
> COALEASCE function is ANSI SQL Standard based and it accepts 1-n arguments it returns first not null value.
答案2
得分: 0
SELECT TOP 1
CASE
WHEN EXISTS(SELECT 1 FROM Student WHERE name = 'Sam') THEN roll_nbr
ELSE 0
END
FROM Student
英文:
SELECT TOP 1
CASE
WHEN EXISTS(SELECT 1 FROM Student WHERE name = 'Sam') THEN roll_nbr
ELSE 0
END
FROM Student
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论