Skip to content
Advertisement

Looping through a column to check if a cast succeeds in SQL Server

I am trying to check if an entire column which is varchar and make sure it can be cast to float. I have a cursor portion like so:

        DECLARE @CastFailed BIT

        SET @CastFailed = (SELECT SUM(CASE WHEN TRY_CAST(@ColumnName AS FLOAT) IS NULL THEN 1
            ELSE 0 END) AS CastResult)

        -- Look at this
        PRINT @CastFailed

        IF @CastFailed > 0
        BEGIN

            PRINT 'ERROR: ' + @ColumnName + ' cannot be converted to FLOAT type'

            SET @HasErrors = 1
   
        END
        ELSE
        BEGIN

            PRINT 'The cast has passed.'

        END

For some reason, it is always returning 1. I already in a previous part of the cursor (not shown but above), verified that the column passed in (@ColumnName) is NOT NULL at any point.

I need to find out if all the CAST to FLOAT for @ColumnName are valid. The cursor loops through a table of columns bring in the FETCH @ColumnName one by one. What am I missing?

Advertisement

Answer

Easy:

DECLARE @t TABLE (txt VARCHAR(100));
INSERT  @t VALUES ('ABC123'),('100.00'),('100'),('11.222.333'),('00');

DECLARE @CastFailed BIT = 
  (SELECT ISNULL(MAX(1),0) FROM @t AS t WHERE TRY_CAST(t.Txt AS FLOAT) IS NULL);

SELECT CastFailed = @CastFailed;

For even better performance …

DECLARE @t TABLE (txt VARCHAR(100));
INSERT  @t VALUES ('ABC123'),('100.00'),('100'),('11.222.333'),('00');

DECLARE @CastFailed BIT = 
  (ISNULL((SELECT TOP(1) 1 FROM 
    (SELECT 1 FROM @t AS t WHERE TRY_CAST(t.Txt AS FLOAT) IS NULL) AS x(x)),0));

SELECT CastFailed = @CastFailed;
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement