Need assistance with querying SQL Server - c#

I am planning for monitoring application which will use SQL Server 2005/08 database. It will monitor old server(s) which are using SQL Server 2000 database. Tools task is to pick the data from the servers do some statistics and insert the data back into tools own database for reporting purpose.
I am using .NET(C#) as development environment.
What I would really like to do is implement stored procedures which will pick the monitoring data from other servers and insert it into the monitoring tools databases table.
Now I would like to know whether its possible to write stored procedure like this ? Or I would have to pick the data from servers in program using one connection and then insert it into tools database using the other connection?
Please let me know if in case you can foresee any complication that I should be aware of.
Also some informative/helpful pointers(links, books) will be helpful.
Thanks all for valuable inputs.

You can do it using stored procedures (assuming both servers can see each other of course), by using Linked Servers.
Once setup, you can query across servers by fully qualifying the object name:
SELECT * FROM [AnotherDbServer].[DatabaseName].[Schema].[TableName]

AdaTheDev's answer is right on, but here are some additional pointers.
Make sure you give the table name an alias if you call out specific columns. Otherwise you will get an error for basically having too many qualifications (4 is the max). Also, if you are linked to an instanced server, make sure you use brackets [ ] in the server name. For example:
SELECT FiscalCalendar.Week, FiscalCalendar.Year
FROM [LinkedServer\Instance].MyDatabase.dbo.FiscalCalendar FiscalCalendar

Related

How can I disable a table in a SQL Server database from SSMS

I inherited a SQL Server database used with a C# client application. I know enough to be dangerous but I'm not a programmer. I know the previous programmer liked to play around in the live database and as a result I have a number of what I think are orphaned tables.
The application itself isn't super high-usage and can withstand the exceptions of tables not being there for a small time frame. I'd like to start turning off or disabling these tables to see they're being used anymore through trial and error.
Is there a way to turn them off without completely removing the data so that I can re-enable them quickly if needed? Or is there a more transparent way to discover whether those tables are needed?
There is no easy way. The tables can be accessed through both stored procedures and direct SQL calls from your client application. A comprehensive approach would mean that you'd have to have some way of making each table unavailable (renaming has been suggested in comments) and then perform a full regression test on your client application; you might have to do this with each table in the database. The client application might access the tables conditionally, subject to external things like the logged-in user (and related privileges), the date, configuration, and so forth.
The SQL Server Profiler is a good tool to use, but it's not going to solve your problem all by itself because you still have to analyze what it captures.
You could create a new db schema and transfer the tables to that schema
ALTER SCHEMA new schema TRANSFER dbo.your table
Then transfer them back again after testing.
https://learn.microsoft.com/en-us/sql/t-sql/statements/alter-schema-transact-sql
You can change the permissions so that no one except you and the dbos have select permission on the table. You cannot prevent a dbo or sa from having all permissions on a table.
You can also encrypt the table see- Encrypting database tables in SQL Server 2008 in which case it is really locked down.
You can also used SQL Server Audit to see if anyone reads the data. Audit is a very low impact product (comes with SQL Server 2008) and is very easy to set up and can audit selects unlike a trigger.

Which one is the best method to replicate a database in SQL Server?

I was wondering which one is the best way to replicate some data of a database to another.
I have a database in one computer and this one receives some transactions. I need to send this data to another server (in the same local network) but with a modified value (I need to add 11 years to a Timestamp value).
So I was looking for some options for my case, I can develop a windows service to do this but I don't know if the sql server replication can do this for me or if there is another option like some kind of magical trigger that can do that.
I'm using SQL Server 2005 on Windows Server 2003 R2.
This link should help you:
Selecting the Appropriate Type of Replication
Quoted summary from link:
Microsoft SQL Server offers three types of replication. Each type of
replication is suited to different application requirements. Depending
on the needs of your application, you can use one or more types of
replication in a topology:
Snapshot replication
Transactional replication
Merge replication
I personally would replicate the database (transactional) and then use log shipping to update the replicated database (on your second server) with the latest data changes (from the primary server) then use a stored procedure running as a sql agent job to update the fields you need.
I personally am not a fan of triggers as you can end up having triggers activating other triggers and something that takes milliseconds to run can take seconds and if you have large volumes of data that can be painful (I manage a system that has exactly this issue - soon to be replaced thankfully)
hope this helps and if you have some follow up questions I'll be happy to help.

Copy data between two SQL Server databases in C#

I have two databases. One of them belongs to a CRM software and is the source.
The other one will be the destination used by a tool I'm developing.
The destination will contain a table ADDRESSES with a subset of the columns of a table of the same name in the source database.
What is the best (most efficient) way to copy the data between those databases (btw: they're on different SQL Server instances if that's important).
I could write a loop which does INSERT into the destination for each row obtained from the source but I don't think that this is efficient.
My thoughts and information:
The data won't be altered on its way from source to destination
It will be altered on its way back
I don't have the complete structure of the source but I know which fields I need and that they're warranted to be in the source (hence, access to the rows obtained from source isn't possible using the index of columns)
I can't use LINQ.
Anything leading me in the right direction here is appreciated.
Edit:
I really need a C# way to copy the data. I also need to know how to merge the copied rows back to the source. Is it really necessary (or even best practise) to do this row after row?
Why write code to do this?
The single fastest and easiest way is just to use SQL Server's bcp.exe utility (bcp: Bulk Copy Program).
Export the data from the source server.
Zip it or tar it if it needs it.
FTP it over to where it needs to go, if you need to move it to another box.
Import it into the destination server.
You can accomplish the same thing via SQL Server Management Studio in a number of different ways. Once you've defined the task, it can be saved and it can be scheduled.
You can use SQL Server's Powershell objects to do this as well.
If you're set on doing it in C#:
write your select query to get the data you want from the source server.
execute that and populate a temp file with the output.
execute SQL Server's bulk insert statement against the destination server to insert the data.
Note: For any of these techniques, you'll need to deal with identity columns if the target table has them. You'll also need to deal with key collisions. It is sometimes easier to bulk load the data into a perma-temp table first, and then apply the prerequisite transforms and manipulations to get it to where it needs to go.
According to your comment on Jwrit's answer, you want two way syncs.
If so, you might want to look into Microsoft Sync Framework.
We use it to sync 200+ tables on Premise SQL to SQL Azure and SQL Azure to SQL Azure.
You can use purely C#. However, it might offer a lot more than you want, or it might be over kill for a small project.
I'm just saying so that you can have different option for your project.
If these databases exist on two servers you can setup a link between the servers by executing sp_addlinkedserver there are instructions for setting this up here. This may come in handy if you plan on regularly "Sharing" data.
http://msdn.microsoft.com/en-us/library/ff772782.aspx
Once the servers are linked a simple select statement can copy the rows from one table to another
INSERT INTO db1.tblA( Field1,Field2,Field2 )
SELECT Field1,Field2,Field2 FROM db2.tblB
If the Databases are on the same instance you only need to execute similar SQL to the above
If this is one time - the best bet is normally SSIS (SQL server integration services), unless there are complex data transformations - you can quickly and easily do column mappings and have it done (reliably) in 15 mins flat......

Data transfer from One database to another

I am looking for an idea or some direction. I have to transfer data from one database to another both are structurally and schema wise same.
Its a complete database with maybe 70 tables and having relationship between tables at different levels. Even though i ' m going to mess up the identity when i move across database but as of now i am ok with it.
Idea which i thought was to load required data from all table into an XML and then create connection to second database and push data from this XML its kind of repeated and not best way at all. So looking for direction.
Can i use entity framework for this somehow??
I cannot use SSIS for this it has to be C# Sorry.
You can create a linked server as stated in the comments to your question. You seemed to indicate that you know how to do this, but in case not, you can do this from SQL Server Management Studio by drilling down to "Server Objects > Linked Servers" beneath your source database on the source database server, then right-click, "New Linked Server", etc.
Then you would use a statement like this, for example, from your C# code:
insert into DestServer.DBName.dbo.TableName
select * from SourceServer.DBName.dbo.TableName
Assuming you are connected to 'SourceServer' and that 'SourceServer' maintains a linked server object pointing to 'DestServer'. Note: you don't actually need to use the fully-qualified name for the table on 'SourceServer', but I've put it there for clarity. I.E. you could also do this:
insert into DestServer.DBName.dbo.TableName
select * from TableName
Don't forget to setup the permissions properly in your linked server object so that your query can write to the table in the destination server. You can do this any number of ways, and often (because I work in a small environment where it's maintained by just me and a couple other folks) I just use the "sa" login:
Yes, can use linked servers in .NET.
You just use the 4 part name.
What you can do in TSQL in SSMS you can do in a .NET SQLcommand.
My experience is that you get better performance connecting to the server you are writing to.

How do you copy a MS SQL 2000 database programmatically using C#?

I need to copy several tables from one DB to another in SQL Server 2000, using C# (VS 2005). The call needs to be parameterized - I need to be able to pass in the name of the database to which I am going to be copying these tables.
I could use DTS with parameters, but I can't find any sample code that does this from C#.
Alternatively, I could just use
drop table TableName
select * into TableName from SourceDB..TableName
and then reconstruct the indexes etc - but that is really kludgy.
Any other ideas?
Thanks!
For SQL Server 7.0 and 2000, we have SQLDMO for this. For SQL Server 2005 there is SMO. This allows you do to pretty much everything related to administering the database, scripting objects, enumerating databases, and much more. This is better, IMO, than trying a "roll your own" approach.
SQL 2000:
Developing SQL-DMO Applications
Transfer Object
SQL 2005:
Here is the SMO main page:
Microsoft SQL Server Management Objects (SMO)
Here is the Transfer functionality:
Transferring Data
How to: Transfer Schema and Data from One Database to Another in Visual Basic .NET
If the destination table is being dropped every time then why not do SELECT INTO? Doesn't seem like a kludge at all.
If it works just fine and ticks all the requirements boxes why create a days worth of work growing code to do exactly the same thing?
Let SQL do all the heavy lifting for you.
You could put the scripts (copy db) found here
http://www.codeproject.com/KB/database/CreateDatabaseScript.aspx
Into an application. Just replace the destination. To actually move the entite database, FOLLOW
http://support.microsoft.com/kb/314546
But remember, the database has to be taken offline first.
Thanks

Categories