views:

394

answers:

1

Hi,

I am trying to write an SQL query within Visual Studio TableAdapter Query Wizard

My SQL query is:

    DECLARE @SQL varchar(255);

SET @SQL = ' SELECT * FROM dbAddress WHERE 1 = 1'

IF @ApexLine1 = ''
    BEGIN
        SET @SQL = @SQL + ' AND addLine1 IS NULL '
    END
ELSE
    BEGIN
        SET @SQL = @SQL + ' AND addLine1 = ''' + @ApexLine1 + ''''
    END

IF @ApexLine2 = ''
    BEGIN
        SET @SQL = @SQL + ' AND addLine2 IS NULL '
    END
ELSE
    BEGIN
        SET @SQL = @SQL + ' AND addLine2 = ''' + @ApexLine2 + ''''
    END

IF @ApexLine3 = ''
    BEGIN
        SET @SQL = @SQL + ' AND addLine3 IS NULL '
    END
ELSE
    BEGIN
        SET @SQL = @SQL + ' AND addLine3 = ''' + @ApexLine3 + ''''
    END

IF @ApexZip = ''
    BEGIN
        SET @SQL = @SQL + ' AND addPostCode IS NULL '
    END
ELSE
    BEGIN
        SET @SQL = @SQL + ' AND addPostCode = ''' + @ApexZip + ''''
    END

IF @ApexCity = ''
    BEGIN
        SET @SQL = @SQL + ' AND addLine4 IS NULL '
    END
ELSE
    BEGIN
        SET @SQL = @SQL + ' AND addLine4 = ''' + @ApexCity + ''''
    END

IF @ApexProv = ''
    BEGIN
        SET @SQL = @SQL + ' AND addLine5 IS NULL '
    END
ELSE
    BEGIN
        SET @SQL = @SQL + ' AND addLine5 = ''' + @ApexProv + ''''
    END

EXEC(@SQL)

I get the error:

'The Declare SQL contruct or statement is not supported'

If I remove the Declare statement I get error:

'The Set SQL construct or statement is not supported'

Is there a work around for this?

Thanks.

+1  A: 

Anything like this:

SET @SQL = @SQL + ' AND addLine1 = ''' + @ApexLine1 + ''''

is EVIL. Don't do it. Variables like @ApexLine1 could contain anything, even something like this:

';DROP TABLE dbAddress--

Think very carefully about what would happen if someone entered something like that in your Address Line 1 field. The only correct solution here is to use the built-in sp_executesql stored procedure. Learn it, use it.

Aside from that, I think at least part of your problem might be that your @SQL variable is only 255 characters. It's easily possible your query is running out of space.

Joel Coehoorn
I am not too worry about the SQL injection issues as the parameters are not being acquired from a textbox or anything. They are being pulled from another database in the code behind. Plus this is a local intranet application that no one outside of our firm has access to. This is just a test query, the 255 characters will be lifted once it is working, but that is not the issue.
Hunter
It doesn't matter if they're pulled from another database. It's still an injection risk (2nd order injection), because _that_ database was likely populated by hand somewhere. And "local intranet" is never an excuse - most attacks are inside jobs. Even if those were valid excuses, why not do it right? It's no harder. What you are doing with that query is just plain **wrong**.
Joel Coehoorn
Point taken. I will take the necessary steps to fix. Thank you.
Hunter