Help with sql statement

  • I am new to vb and sql . please bear with me

    I have a database name database 1. I have column name "column A" and “column B" in all tables. I want to retrieve tables name and sum of (column A – column B) of all tables like below

    table1 ( columnA - columnB)

    table2 ( columnA - columnB)

    table3 ( columnA - columnB)

    if i have some manageable table I can use table names in sql statement

    like bellow

    SELECT "Table1" AS Table, SUM(a) - SUM(b) AS Result FROM table1

    UNION

    SELECT "Table2", SUM(a) - SUM(b) FROM table2

    UNION

    SELECT "Table3", SUM(a) - SUM(b) FROM table3

    I would like to know is it possible to create a cursor to dynamically collect the data from all tables ?

    I have tried the following code, When I run the sql statement I get the following error

    Syntax error (missing operator) in query expression 'GROUP_CONCAT(COLUMN_NAME ORDER BY COLUMN_NAME SEPARATOR ' - ')'.

    Dim CmdStr As String = "SELECT TABLE_NAME, GROUP_CONCAT(COLUMN_NAME ORDER BY COLUMN_NAME SEPARATOR ' - ')FROM INFORMATION_SCHEMA.COLUMNS WHERE COLUMN_NAME IN ('a','b')AND TABLE_SCHEMA='database1'GROUP BY COLUMN_NAME;"

    or is there any way to do it in vb.net and ms access database? any bit of info would be helpful

  • So here is the answer you did not expect: in a relational database a table is supposed to model a unique entity, and each column is supposed to model a unique attribute of that entity. Given this, the question you ask does not make much sense. Yes, it is possible to do, but it is not a good exercise for a beginner, because it will lead into paths where you should not wander at this point.

    My assumption is that you do this as some kind of exercise to learn, but it is not a good exercise where you are now.

    [font="Times New Roman"]Erland Sommarskog, SQL Server MVP, www.sommarskog.se[/font]

  • Thanks for your response.

    before giving up on it , I am still curious to know is there any way to fix the sql query?

  • The query you posted uses group_concat() which is not a function in SQL Server. That smells MySQL to me, but I could be wrong. Furthermore, the error message you posted is not from SQL Server. (And this is an SQL Server forum.)

    Here is a way to write this query in SQL Server, but which will not work in any other product:

    SELECT TABLE_NAME, substring(collist, 1, len(collist) - 2)

    FROM INFORMATION_SCHEMA.TABLES T

    CROSS APPLY (SELECT COLUMN_NAME + ' - '

    FROM INFORMATION_SCHEMA.COLUMNS C

    WHERE T.TABLE_NAME = C.TABLE_NAME

    AND C.COLUMN_NAME IN ('a', 'b')

    FOR XML PATH('')) AS C (collist)

    WHERE collist IS NOT NULL

    [font="Times New Roman"]Erland Sommarskog, SQL Server MVP, www.sommarskog.se[/font]

  • Have you explored the option of CTE .

Viewing 5 posts - 1 through 4 (of 4 total)

You must be logged in to reply to this topic. Login to reply