Friday, March 9, 2012

How to use IF..THEN to select SQL Server/Database?

I have a single form that the users can do lookups for items. We have two locations each with its own SQL Server and database. Trying to use an IF...THEN statement as they select the DB they want to query it then creates the connection string for that particular database. I haven't a clue on how to do this. If someone could point me to the documentation to do this I would really appreciate it.

<%@. Page Language="VB" %><%@. ImportNamespace="System.Data" %><%@. ImportNamespace="System.Data.OleDB" %><%@. ImportNamespace="System.Data.SqlClient" %><!DOCTYPE html PUBLIC"-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><script runat="server">Sub get_Dies(ByVal senderAs System.Object,ByVal eAs System.EventArgs)Dim dbConnectionAs New SqlConnectionIf ddlDatabase.SelectedValue ="db2"Then ? dbConnection ="server=server2;Database=db2;UID=user;PWD=pass" dbConnection.Open()Else ? dbConnection ="server=server1;Database=db1;UID=user;PWD=pass" dbConnection.Open()End If Dim sqlStringAs String =" sql statement"Dim dbCommandAs New SqlCommand(sqlString, dbConnection)Dim dbDataReaderAs SqlDataReader dbDataReader = dbCommand.ExecuteReader(CommandBehavior.CloseConnection) gvDies.DataSource = dbDataReader gvDies.DataBind() dbConnection.Close()End Sub </script><html xmlns="http://www.w3.org/1999/xhtml" ><head runat="server"> <title>Die Usage Lookup</title><link rel="stylesheet" href="/intranet.css" type="text/css" /></head><body> <form id="form1" runat="server"> <div> Find dies matching: <asp:TextBox ID="tbDies" runat="server" /><br />Select database: <asp:DropDownList id="ddlDatabase" runat="server" AutoPostBack="true" OnSelectedIndexChanged="get_Dies"> <asp:ListItem Text="" Selected="true" Value="" /> <asp:ListItem Text="DB1" Value="db1" /> <asp:ListItem Text="DB2" Value="db2" /> </asp:DropDownList> <asp:gridview ID="gvDies" runat="server" GridLines="none" > </asp:gridview> </div> </form></body></html>

in your if statement you can assign the connectionstring to the connection object such as:

Dim connectionStringAsString

If ddlDatabase.SelectedValue ="db2"Then
connectionString ="server=server2;Database=db2;UID=user;PWD=pass"
Else
connectionString ="server=server1;Database=db1;UID=user;PWD=pass"
End If

Dim dbConnectionAs New SqlConnection(connectionString)

dbConnection.Open()


|||

That is brilliant!! Did exactly what I was looking for. Thank you very much.

No comments:

Post a Comment