我是 sql 新手,我想过滤 select 语句的结果。我想隐藏特定列的值,以防另一列(同一行)中存在特定值。 例如,我希望 Products.product 列隐藏或为空,以防 Products.active 列中的值为 false : 预先感谢
SELECT Products.product,Products.Active,
CASE Products.product
WHEN 'false' THEN Products.Active = ''
END
FROM Products
SELECT Products.Active,
CASE Products.Active
WHEN 'false' THEN ''
ELSE Products.product
END AS 'HIDDEN COLUMN'
FROM Products
您可能希望使用
WHERE
子句而不是 CASE
来消除整个记录。如果您确实想要记录并且只想将此字段为空,请使用以下 CASE
语句:
CASE Products.Active
WHEN false
THEN null
ELSE Products.product
END
--这仅显示不为空的列,但可以根据不同的条件进行修改。
创建或更改过程listcols_dynamic为 --在 AI bing 的帮助下创建 开始 声明 @sql NVARCHAR(MAX) = 'SELECT '; 声明 @columns NVARCHAR(MAX) = '';
--Initial Columns
SET @columns = 'static_field1, static_field2, '
IF EXISTS (SELECT 1 FROM mytable WHERE Col_1 IS NOT NULL)
SET @columns = @columns + 'Col_1, ';
IF EXISTS (SELECT 1 FROM mytable WHERE Col_2 IS NOT NULL)
SET @columns = @columns + 'Col_2, ';
IF EXISTS (SELECT 1 FROM mytable WHERE Col_3 IS NOT NULL)
SET @columns = @columns + 'Col_3, ';
IF EXISTS (SELECT 1 FROM mytable WHERE Col_4 IS NOT NULL)
SET @columns = @columns + 'Col_4, ';
IF EXISTS (SELECT 1 FROM mytable WHERE Col_5 IS NOT NULL)
SET @columns = @columns + 'Col_5, ';
-- Remove the trailing comma and space if necessary
if right(@columns,2)=', '
SET @columns = LEFT(@columns, LEN(@columns) - 1);
-- Complete the SQL statement
SET @sql = @sql + @columns + ' FROM mytable';
--Debug
--print @sql;
-- Execute the dynamic SQL
EXEC sp_executesql @sql;
结束;