i have an idea to call two values from two different databases and comapre them in one statement? is it possible?
i am working with c# and MS-SQL
Yes.
For MSSQL you can add the database name in front of your table. You normally have 4 namespaces you can use
[Server name].[database name].[owner].[table_name]
So if you want to compare two values in the one statement you should only need to join across the tables by placing the database name in front of the table name.
If the databases are on different servers then you will need to create a linked server to the side which will run your SQL so that its aware of the other sql server. You can add linked servers in Management studio or via SQL using something like sp_addlinkedserver
You may do cross database joins to compare these values:
SELECT
db1.Value as value1,
db2.Value as value2
FROM
[database1].dbo.MyTable1 as db1
INNER JOIN
[database2].dbo.MyTable as db2
ON
/* insert join clasue */
There are a few possibilities here depending on your setup. If your databases are different SQL Server installations then you will want to look at sp_linkedserver first. Once you have the ability to see both databases using the same login you could just execute the following query where db1 and db2 are the databases, dbo is the owner and tab1 and tab2 are the respective tables.
SELECT a.col1
FROM db1.dbo.tab1 a, db2.dbo.tab2 b
WHERE a.col1 = b.col2
If you should happen to lack the SQL Server permissions to create a linked server, you could create connections to each server and your client could attach to the servers using Microsoft JET library, and then you could perform the heterogeneous join client-side.
Related
I want to do what SQL MERGE...WHEN MATCHED...WHEN NOT MATCHED does,
but with the source and destination tables on different Azure databases. (Typically on the same server if that helps.)
The source and destination tables are not exactly the same, that's why SQL MERGE would be perfect. (I can decide what column to match on, and which columns to use in the INSERT or UPDATE.)
If this can not be done in SQL, I could load the tables into my C# code and do the merge there (will affect performance though). Does anyone know if .NET has something similar to SQL MERGE in ADO.NET (merging DataTables).
Thanks for any help!
Edit: this image shows the tables before MERGE (all Values are int):
This image shows the MERGE statement and the resulting source and dest:
Azure SQL database doesn't support across database operations directly, even these databases are in the same Azure SQL Server. it will throw below error.
To work around this Azure SQL database only support the across database query with elastic query
Example
CREATE MASTER KEY; -- create master key
GO
-- credential maps to a login or contained user used to connect to remote database
CREATE DATABASE SCOPED CREDENTIAL CrossDbCred1 -- credential name
WITH IDENTITY = 'username', -- login or contained user name
SECRET = '**********'; -- login or contained user password
GO
-- data source to remote Azure SQL Database server and database
CREATE EXTERNAL DATA SOURCE source
WITH
(
TYPE=RDBMS, -- data source type
LOCATION='server.database.windows.net', -- Azure SQL Database server name
DATABASE_NAME='database1', -- database name
CREDENTIAL=CrossDbCred1 -- credential used to connect to server / database
);
GO
-- external table points to table in an external database with the identical structure
CREATE EXTERNAL TABLE [dbo].[source]
(
[Id] [varchar](50),
[value1] [int],
[value2] [int],
[value3] [int]
)
WITH (DATA_SOURCE = [source], -- data source
SCHEMA_NAME = 'dbo', -- external table schema
OBJECT_NAME = 'source' -- name of table in external database
);
GO
Now we can test our Elastic Query to merge tables.
MERGE into destination1 B
USING source E
ON (B.Id = E.Id)
WHEN MATCHED THEN
UPDATE SET value2 = E.value2, value3 = E.value3
WHEN NOT MATCHED THEN
INSERT (Id,value2,value3) VALUES (Id,value2,value3);
Output
Before merging
After merging
My query is when I install this application on some system with SQL Server install I should get all databases in a combobox.
Login image
In the first combobox (Select database type) we have option to select the SQL Server. When I will select the SQL Server, I wish that the available instance of the database like root or something else should come in second combobox. And we should get the database name of the all database in the 3rd combobox
To list the instances of Sql Server you can use:
SQLCMD -L
By executing it in a process and collect the output.
For listing of the databases you can use this select statement:
SELECT name FROM master.dbo.sysdatabases
or
EXEC sp_databases
The problem is, you need to be logged in to the database to get the list of databases which the logged in user is allowed to see. I think you need to consider it in your application.
I Have two copies of the same sql server database (DB1 & DB2). What is the best way to do the following :
Update the data of some tables in DB2 To be the same as DB1 (ie: DB1 is the source And DB2 is the destination)
and update the data of some other tables in DB1 to be the same as DB2 (ie: DB2 is the source And DB1 is the destination)
How to make this using c# program? hope to help me in the best soulution to do that.
keep in mind that there is no connection between the program and the two copies at the same time and the tables has many relations up on Identity columns
Thanks :)
My suggestion would be to setup a linked server and then create stored procedure that make use of MERGE SQL command.
Note this is semi pseudo code example
MERGE DB2 AS target
USING DB1 AS source
ON <Primary Keys>
WHEN MATCHED THEN
UPDATE SET Key = source.Value
WHEN NOT MATCHED THEN
INSERT (<Columns>)
VALUES (source.values)
OUTPUT deleted.*, $action, inserted.* INTO #MyTempTable;
Then you can create a SqlConnection/SqlCommand and then call the stored procedure. This code you can ultimatelt host in a windows service or normal .Net event i.e. button click, OnLoad as example.
I created a windows forms application in C #, and a database MS SQL server 2008 Express, and I use LINQ-to-SQL query to insert and edit data.
The database is housed on a server with Windows Server 2008 R2 (standard edition). Right now I have the application running on five different computers, and users are authenticated through active directory.
One complaint reported to me was that sometimes when different data is entered and submitted, the same data do not appear in the listing that contains the application. I use try catch block to send the errors but errors do not appear in the application; but the data simply disappear.
The id of the table records is an integer auto-increment. As I have to tell them the registration number that was entered I use the following piece of code:
try{
ConectionDataContext db = new ConectionDataContext();
Table_Registers tr = new Table_Registers();
tr.Name=textbox1.text;
tr.sector=textbox2.text;
db.Table_Registers.InsertOnSubmit(tr);
db.SubmitChanges();
int numberRegister=tr.NumberRegister;
MessageBox.Show(tr.ToString());
}
catch{Exception e}
I wonder if I'm doing something wrong or if you know of any article on the web that speaks how to insert data from different clients in MSSQL Server databases, please let me know.
Thanks.
That's what a database server DOES: "insert data simultaneously from different clients".
One thing you can do is to consider "transactions":
http://www.sqlteam.com/article/introduction-to-transactions
Another thing you can (and should!) do is to insure as much work as possible is done on the server, by using "stored procedures":
http://www.sql-server-performance.com/2003/stored-procedures-basics/
You should also check the SQL Server error logs, especially for potential deadlocks. You can see these in your SSMS GUI, or in the "logs" directory under your SQL Server installation.
But the FIRST thing you need to do is to determine exactly what's going on. Since you've only got MSSQL Express (which is not a good choice for production use!), perhaps the easiest approach is to create a "log" table: insert an entry in your "log" every time you insert a row in the real table, and see if stuff is "missing" (i.e. you have more entires in the log table than the data table).
With SQL Server I run this query with no problem...
SELECT SUM(Esi) AS Dispo
FROM [mdb].[dbo].[Query1] AS A
INNER JOIN [mdb2].[dbo].[TieCol] as B ON A.Alias=B.IDAlias
WHERE Alias LIKE 'SETUP%'
I join two tables that reside in two different databases (mdb and mdb2).
But how can I do it in my .NET application?
When I need to use this statement
string cmdText = "SELECT SUM(Esi) AS Dispo
FROM [mdb].[dbo].[Query1] AS A
INNER JOIN [mdb2].[dbo].[TieCol] as B ON A.Alias=B.IDAlias
WHERE Alias LIKE 'SETUP%'";
this.OP = new SqlConnection(ConfigurationManager.ConnectionStrings["mdb2"].ConnectionString);
SqlCommand sqlCommand = new SqlCommand(cmdText, this.OP);
I can't execute it, since this.OP is the connection to mdb2... And for mdb?
How can I connect to both databases simultanously?
The SQL connection is to the server - the Initial catalog in a connection string behaves like use - it sets the default DB.
So your 3 part SQL query should work as is. So possibly
Make sure that the SQL login used by your app (or the account of your AppPool if using Web and Integrated Security) has the necessary access to both databases. (use RunAs on SQL Enterprise Manager as this account and try to run the query)
You might try escaping [Alias]
Also, if there is coupling between mdb1 and mdb2 (e.g. SPROCS in mdb1 use tables in mdb2 etc), for ease of maintenance, you might consider adding views in mdb1 for mdb2 objects. This allows for easy identification of cross-database dependencies. In this case, your query can use views which look like they are in the same database, although the underlying dependency on mdb2 is still there.
I'm not sure if there is a way to do this within the connection string. But you can probably do it using a four part reference to the table: [server].[database].[table].[column].
Your C# application only need to connect to one database server for this query.
Say your C# application connect to [mdb]. Database [mdb2] should b linked server in database [mdb].
Since you can run that query in sql server, so there must be one sql server connected to both databases. use that sql server in your C# connection string. That's it!