SQL Server查询编写需求:cashierid=007时cashiername显示N/A
Got it, let's work through this query requirement. You want to show N/A for the cashiername column whenever cashierid equals '007', and display the actual cashiername value for all other cases. Here are two reliable approaches you can use in SQL Server:
1. Using the CASE Statement (Standard SQL, Wide Compatibility)
The CASE statement is the most portable option—it works across all SQL versions, including older ones that don't support newer functions. Here's how to implement it:
SELECT cashierid, CASE WHEN cashierid = '007' THEN 'N/A' ELSE cashiername END AS cashiername FROM your_table_name; -- Replace with your actual table name
Quick Notes:
- If
cashieridis a numeric data type (likeINT), drop the single quotes around '007' (use007instead—though keep in mind numeric types don't retain leading zeros, so you might want to double-check the column's data type here). - Don't forget to swap
your_table_namewith the real name of your table containing these columns.
2. Using the IIF Function (SQL Server 2012+)
If you're running SQL Server 2012 or later, the IIF function offers a more concise way to write simple conditional logic:
SELECT cashierid, IIF(cashierid = '007', 'N/A', cashiername) AS cashiername FROM your_table_name; -- Replace with your actual table name
This does exactly the same thing as the CASE statement but in a more compact form. Pick whichever version feels more readable for your workflow.
内容的提问来源于stack exchange,提问作者user9480404

