Results 1 to 2 of 2

Thread: SQL if statement...

  1. #1

    Thread Starter
    Addicted Member
    Join Date
    May 2006
    Posts
    170

    SQL if statement...

    I have an SQL statement that gathers the users fullname from a userTbl table using the userID value in the commentsTbl table. What I want to be able to do is if the value of commentsTbl.isPublishedComm equal to 'True' then add a value into the FullName field e.g. 'NOT FOUND' else if commentsTbl.isPublishedComm equal to 'False' then use LEFT OUTER JOIN code.

    Code:
    SELECT commentsTbl.ID, commentsTbl.commID, commentsTbl.commArea,commentsTbl.isPublishedComm, userTbl.userFirst + ' ' + userTbl.userLast AS FullName
    FROM commentsTbl LEFT OUTER JOIN userTbl ON commentsTbl.userCreatedID = userTbl.ID WHERE commentsTbl.commArea = 'UK'
    So would be something like

    Code:
    If commentsTbl.isPublishedComm = 'True' then
    SELECT commentsTbl.ID, commentsTbl.commID, commentsTbl.commArea,commentsTbl.isPublishedComm, 'NOT FOUND' AS FullName
    FROM commentsTbl LEFT OUTER JOIN userTbl ON commentsTbl.userCreatedID = userTbl.ID WHERE commentsTbl.commArea = 'UK'
    elseif commentsTbl.isPublishedComm = 'False' then
    SELECT commentsTbl.ID, commentsTbl.commID, commentsTbl.commArea,commentsTbl.isPublishedComm, userTbl.userFirst + ' ' + userTbl.userLast AS FullName
    FROM commentsTbl LEFT OUTER JOIN userTbl ON commentsTbl.userCreatedID = userTbl.ID WHERE commentsTbl.commArea = 'UK'
    endif
    Thanks

    Simon

  2. #2
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,222

    Re: SQL if statement...

    You just use one SELECT statement as normal but, for that column in the result set, you use a CASE expression:
    Code:
    ColumnA,
    ColumnB =
        CASE commentsTbl.isPublishedComm
            WHEN 'True' THEN 'NOT FOUND'
            ELSE userTbl.userFirst + ' ' + userTbl.userLast
        END,
    ColumnC
    By the way, using a text column containing 'True' and 'False' is very dodgy. If that's what you're doing and you have control over the database then change it and do it properly with a bit column.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width