Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specify Sql Server Schema in connectionString C#

I have got a console app that is connecting to a Sql Server and getting some values. I have the Schema in the Select(dbo):

        var ds = new DataTable("test");
        var connSqlRemoto = new SqlConnection("Server=myserverIP;Database=myDataBase;User Id=user;Password=pass;Integrated Security=False;Connection Timeout=60");
        connSqlRemoto.Open();
        var nombreBbdd = connSqlRemoto.Database;
        var daASqlRemoto = new SqlDataAdapter();
        var cmdSqlRemoto = new SqlCommand("SELECT * FROM " + nombreBbdd + ".dbo.myTable;", connSqlRemoto);
        cmdSqlRemoto.CommandTimeout = 1200;
        cmdSqlRemoto.Parameters.Clear();
        daASqlRemoto.SelectCommand = cmdSqlRemoto;
        daASqlRemoto.Fill(ds);

I want the Schema to be dynamic. Is it possible to pass the Schema in the connection string? Something like this is not working:

 Server=myserverIP;Database=myDataBase/dbo;User Id=user;Password=pass;Integrated Security=False;Connection Timeout=60

or

Server=myserverIP;Database=myDataBase.otherSchema;User Id=user;Password=pass;Integrated Security=False;Connection Timeout=60

Thanks.

like image 748
Za7pi Avatar asked Sep 21 '26 04:09

Za7pi


2 Answers

Probably the easiest way to achieve a per-connection schema selection is to map your schema onto users, and connect to the database using the correct user. This will mean they will automatically query their default schema.

like image 137
PhillipH Avatar answered Sep 22 '26 19:09

PhillipH


No. You can not pass schema with connection string. But you can pass schema in sqlcommand like this.

var schema=".dbo." -- you can set it globally or can change dynamically
cmdSqlRemoto = new SqlCommand("SELECT * FROM " + nombreBbdd + schema + "myTable;", connSqlRemoto);
like image 40
Deepak Sharma Avatar answered Sep 22 '26 18:09

Deepak Sharma



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!