如何查询表中的字段?

时间:2018-02-01 22:39:43

标签: sql sql-server excel-vba vba excel

我在SQL Server中有一个看起来像这样的表。

enter image description here

我想知道是否有办法创建SQL来遍历每个源表,识别相关字段,并根据字段执行计数。因此,例如,我想查看名为“US_SCM”的表和名为“DESCR”的字段,并获取所有记录的总数。然后,对于同一个表和字段,计算所有空值。然后,对于相同的表和字段,计算所有负数。然后,对于此表和字段,计算所有正数,依此类推。计算空值,负数,正数等是很简单的,但我想知道如何编写一些代码来遍历表中的记录,并完成所有这些计数。我可以使用SQL或VBA来完成任务。我不确定动态SQL会是什么样子,无论如何都可能很难做到这一点,但我绝对愿意接受这些想法!如果我沿着VBA路径前进,我认为代码看起来就像下面的示例,但这确实需要某种点缀!

Sub Download_Standard_BOM()
'Initializes variables
Dim cnn As New ADODB.Connection
Dim rst As New ADODB.Recordset
Dim ConnectionString As String
Dim StrQuery As String

Dim rCell As Range
Dim rRng As Range
Dim sht As Worksheet
Dim LastRow As Long
Dim i As Long

'Setup the connection string for accessing MS SQL database
Set cnn = New ADODB.Connection

'For a trusted Connection, where your user ID has permissions on the SQL Server:
cnn.Open ConnectionString:="Provider=SQLOLEDB.1;" & _
"Data Source=" & "Server_Name" & ";Initial Catalog=" & "DB_Name" & _
";TRUSTED_CONNECTION=YES"

cnn.CommandTimeout = 900

Set sht = ThisWorkbook.Worksheets("Sheet1")

LastRow = sht.Cells(sht.Rows.Count, "A").End(xlUp).Row

    Set rRng = sht.Range("B2:B" & LastRow)
    i = 2
    For Each rCell In rRng.Cells

        On Error Resume Next
        StrQuery = rCell.Value

            StrQuery = "Select COUNT(" & rCell.Offset(0, 1) & ")"
            StrQuery = StrQuery & "FROM " & rCell.Value & """"

                rst.Open StrQuery, cnn

            i = i + 1
            rst.Close
    Next rCell

End Sub

非常感谢所有关注此事的人!

1 个答案:

答案 0 :(得分:1)

我会在你的图片中查询该表并将其作为记录集返回。然后遍历记录集并将第二个sql语句拼接在一起。执行第二个sql语句并获取返回的值,将结果写入Sheet1(或其他)。

这看起来像是:

Sub Download_Standard_BOM()
    'Initializes variables
    Dim cnn As ADODB.Connection
    Dim rst_tables As ADODB.Recordset
    Dim rst_results as ADODB.Recordset
    Dim ConnectionString As String
    Dim StrQuery As String


    Dim sht As Worksheet
    Dim LastRow As Long 

    'Setup the connection string for accessing MS SQL database
    Set cnn = New ADODB.Connection

    'For a trusted Connection, where your user ID has permissions on the SQL Server:
    cnn.Open ConnectionString:="Provider=SQLOLEDB.1;" & _
    "Data Source=" & "Server_Name" & ";Initial Catalog=" & "DB_Name" & _
    ";TRUSTED_CONNECTION=YES"

    cnn.CommandTimeout = 900

    Set sht = ThisWorkbook.Worksheets("Sheet1")

    'we will be writing out to this lastrow
    LastRow = sht.Cells(sht.Rows.Count, "A").End(xlUp).Row  


    'Write a query to get this sql server table from your picture
    StrQuery = "Select * FROM theTableInYourPicture;"

    rst_tables.Open StrQuery, cnn

    'Check to make sure we got some database
    If rst_tables.EOF and rst_tables.BOF Then 
        msgbox("Couldn't retrieve any data from that table from your picture");
        exit sub
    End if

    'Still here? Lets loop through this recordset
    Do While Not rst_tables.eof

        tablename = rst_tables.Fields("Source_Table").value
        columnname = rst_tables.Fields("Source_Column_Name").value

        'write it out
        sht.cells(lastrow, 1).value = tablename
        sht.cells(lastrow, 2).value = columnname

        'Now set up some sql to get the values you want
        strSQL="SELECT "
        strSQL=strSQL & "   count(distinct " & columnName & ") as [Total Counts], "
        strSQL=strSQL & "   SUM(CASE WHEN " & columnName & " IS NULL THEN 1 ELSE 0 END) as Nulls, "
        strSQL=strSQL & "   SUM(CASE WHEN " & columnName & " < 0 THEN 1 ELSE 0 END) as NegativeNumbers, "
        strSQL=strSQL & "   SUM(CASE WHEN " & columnName & " > 0 THEN 1 ELSE 0 END) as PositiveNumbers "
        strSQL=strSQL & "   SUM(CASE WHEN " & columnName & "=0 THEN 1 ELSE 0 END) as ZERO "
        strSQL=strSQL & "FROM "
        strSQL=strSQL & "   " & tablename & ";"

        'got get it
        Set rst_results = New ADODB.Recordset
        rst_results.open strSQL, cnn

        'Did it return anything?
        if rst_results.eof and rst_results.eof Then
            'poop. got nothing
            sht.Cells(lastRow, 3).value = "NO RESULTS!"
        else
            'great! we got something. write it out
            sht.cells(lastRow, 3).copyFromREcordset rst_results
        End if

        'Close the recordset
        rst_results.close

        'increment the row to which we are writing
        lastRow = lastRow + 1

        'increment to the next table/record
        rst_tables.movenext
    Next rCell

End Sub