How Can we use ISNULL to all Column Names in SQL Server 2008?

前端 未结 2 445
暖寄归人
暖寄归人 2021-01-02 00:56

I have a question

I tried to google it but looks like they don\'t like *

I\'m using SQL Server 2008.

I have the following

相关标签:
2条回答
  • 2021-01-02 01:28

    Try this...

    ISNULL (COALESCE (column1, column2), 'No Data')
    

    You would need to include all column names though, you can't use *

    COALESCE returns the first non-null value in its argument list so if they are all null it will return null

    0 讨论(0)
  • 2021-01-02 01:35

    You can use ISNULL multiple times in the same SQL statement for different columns, but you must write it separately for each column:

    SELECT
        ISNULL(ProductName, 'No Data') AS ProductName,
        ISNULL(CAST(UnitPrice AS NVARCHAR), 'No Data') AS UnitPrice, 
        ISNULL(CAST(UnitsInStock AS NVARCHAR), 'No Data') AS UnitsInStock,
        ISNULL(CAST(UnitsOnOrder AS NVARCHAR), 'No Data') AS UnitsOnOrder
    FROM tbl
    

    If you are building a dynamic SQL query, you could theoretically gather a list of columns in the table and generate a query with ISNULL on each one. For example:

    DECLARE @SQL nvarchar(max)
    
    SET @SQL = 'SELECT '
    
    SELECT @SQL = @SQL + 'ISNULL(CAST([' + sc.name + '] AS NVARCHAR), ''No Data'') AS [' + sc.name + '],'
    FROM sys.objects so
    INNER JOIN sys.columns sc ON sc.object_id = so.object_id
    WHERE so.name = 'tbl'
    
    -- Remove the trailing comma
    SELECT @SQL = LEFT(@SQL, LEN(@SQL) - 1) + ' FROM tbl'
    
    EXEC sp_sqlexec @SQL
    

    This code has problems when converting some column types like timestamps to an nvarchar, but it illustrates the technique.

    Note that if you had another column that should be returned if a value is null, you could use the COALESCE expression like this:

    SELECT COALESCE(ProductName, P_Id) AS Product...
    
    0 讨论(0)
提交回复
热议问题