开发者

Parametrized table name in SQL query

I'm using Vb2005 to hit a SQL server. i have a pretty complicated query that hits identically structured databases on the server. I was looking into parameterizing the FROM clause but cant seem to do it. here is what i was trying

    Dim sql As String = "SELECT * " & _
                        "FROM [@DB].[dbo].[Trips] AS T " & _
                        "WHERE T.DepartTime >= CONVERT(DATETIME, 'Sep 08, 2011', 120);"

    Dim cmd As New System.Data.SqlClient.SqlCommand(sql, conn)
    cmd.Parameters.Add("@DB", SqlDbType.Char)
    cmd.Parameters("@DB").Value = "DriverDb"

Depending on the users needs I will hit the 'DriverDb' or the 'MaintDb' or 'DispDb' databases. the SQL string is actually much more complicated than that with references to the db in about 5 places so wanted to simplify it so that i could just replace with a para开发者_StackOverflowmeter.


I guess we can't do that for the DB name or table name which may not be considered as parameters. My suggestion would be to use a variable "db" and append that to the string "sql" something like below

Dim db As String = "DriverDb";
Dim sql As String = "SELECT * " & _  
                    "FROM ["& db &"].[dbo].[Trips] AS T " & _                         
                     "WHERE T.DepartTime >= CONVERT(DATETIME, 'Sep 08, 2011', 120);"

Hope this helps!!


The following question's answer seems to sum it up pretty well. Dynamic SQL (passing table name as parameter) You really should avoid dynamic SQL like this if at all possible.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜