I'm trying to query an SQL Server database and I wondered if there was some
kind of if function that I could use.
Here's my code (stripped down a bit and cobbled together from various
sources):
Sub ADOImportFromDB()
Dim cn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim intColIndex As Integer
Dim TargetRange As Range
Dim strSQL As String
ActiveSheet.Cells.Clear
Set TargetRange = ActiveSheet.Cells(1, 1)
strSQL = "SELECT "
strSQL = strSQL & "jch.DESCRIPTION Description "
strSQL = strSQL & ", jct.COST_CODE CostCode "
strSQL = strSQL & ", jct.CLASS Class"
strSQL = strSQL & ", jct.AMOUNT Amount "
'********************************** 'HERE'S WHAT I WOULD LIKE TO DO
'strSQL = strSQL & ", iif(jct.CLASS='16', jct.AMOUNT, -jct.AMOUNT) as
AdjAmount "
strSQL = strSQL & "FROM "
strSQL = strSQL & "JC_HEADERMASTER jch"
strSQL = strSQL & ", JC_TRANSACTIONS jct "
strSQL = strSQL & "WHERE "
strSQL = strSQL & "jch.JOB = jct.JOB "
' open the database
Set cn = New ADODB.Connection
With cn
.Provider = "SQLOLEDB"
.ConnectionString = _
"DSN=myDSN;UID=myusername;PWD=mypassword;DATABASE=mydatabase;Network=DBMSSOCN;Address=servername,1433"
.Open
End With
Set rs = New ADODB.Recordset
With rs
.Open strSQL, cn, , , adCmdText
For intColIndex = 0 To rs.Fields.Count - 1 ' the field names
TargetRange.Offset(0, intColIndex).Value =
rs.Fields(intColIndex).Name
Next
TargetRange.Offset(1, 0).CopyFromRecordset rs ' the recordset data
End With
rs.Close
Set rs = Nothing
cn.Close
Set cn = Nothing
End Sub
The query works fine without the line in question.
Googling suggests things like IF, IIF, DECODE, CASE, but I can't seem to put
these into practice.
I know I could pull the data in and then do my if within Excel, but it seems
to me to be better practice to do this in the query, if possible.
Any suggestions? Or should I do this in Excel instead? Jamie?
Thanks
--
Dianne
Bookmarks