How to check if a database exists? - c#

I want to check if a database is working as a "Publisher" to other databases.
To do this I was planing on checking if the database "distribution" exists on that instance.
after reading this I thought I could just do
new Sqlcommand("SELECT name FROM master.dbo.sysdatabases WHERE name = #name")
and solve my problem...but I dont have that table in my database...:s
is there another way to solve my problem?

If you want to know if a database is a publisher then looking for a distributor is the wrong check. A database can have a remote distributor, in which case you'll get a false negative. Or the distributor may exist but the database may not be a publisher, in which case you get a false positive. Not to mention that the distribution DB may have any name, so looking for a database named distribution is also wrong.
The proper way to do it is to sue the built in replication helper procedures:
exec sp_helppublication will return information about all publications in a database. IF the database is not a publisher, it won't return anything (yoru cue to action).
exec sp_helpdistributor will return information about the distributor of a publisher
exec sp_helpdistributiondb will return information about a distribution database
In addition, the simple facts whether the DB is a publisher, subscriber or distributor can be discovered in sys.databases:
is_published Database is a publication database in a
transactional or snapshot replication topology.
is_merge_published Database is a publication database in a merge replication topology.
is_subscribed Database is a subscription database in a
replication topology.
is_distributor Database is the distribution
database for a replication topology.

Assuming you have sufficient permissions to view database metadata you can use
SELECT CASE
WHEN DB_ID('distribution') IS NULL THEN 0
ELSE 1
END AS distributionExists

select *
from sys.databases
where name = #name
Very close. It looks like that is SQL Server 2000 catalog view. What you are looking for is querying sys.databases.

Related

How can I access all databases in SQL Server Management Studio?

I'm working on a query editor in which user enters a SQL query and in code behind I pass this query to a SqlCommand and execute it and display result to the user.
But there is one problem: how can I access all the databases in SQL Server which the user created? How can I set initial catalog= to access all databases in SQL Server, so that user enters any query, then it will be execute against all those databases.
For example:
use db_compiler
select * from std
use student
select * from student
So I'm going to say this - what you are requesting to do is a fundamentally BAD idea. SQL Injection is a concern among many, many other things.
However, if you want a list of the databases to set initial catalog, check out the answer to this question:
SQL Server query to find all current database names
you don't require to set initial catalog in order to be able to access to other databases.
Ability to access other database is determine by the permission of the login. If the login is able has the permission to access to other database, you can you use the 3 part naming convention to access it.
Example, even if the initial catalgo is DB1, it will be to access the TABLE3 in DB2
SELECT *
FROM [DB2].[SCHEMA].[TABLE3]
For example instead of
use db_compiler
select * from std
you can
select *
from db_compiler.dbo.std

How to export database and import it locally by C# code?

How to "clone" a database from a remote server to LocalDB database by a C# application? No relationships back to the remote database are needed.
Background
Application is written in C# using .NET 4.5.2 and supports two modes - online which connects to a remote MS SQL Server database, and offline which connects to a LocalDB database. The application primarily targets newer versions of the servers (if it matters, supporting only version 2014 is ok).
Before the user goes offline it should ask the application to clone the remote database to the LocalDB database (the local database is completely overwritten). The local database should be independent on the remote database, i.e. no slave nor replication.
Both the online and offline connection string contains name of the respective database. The application itself has no direct knowledge of the database name nor of the table names as this is managed by the connection strings and by the Entity Framework.
Question
How to "clone" the remote database to a LocalDB database (the remote database name and the LocalDB database name might be different)?
I prefer a solution which does not require to launch an external program, but this is not a hard requirement.
Issues
Copying through Entity Framework no tracking entities is unacceptable slow.
I am aware of the BACKUP DATABASE and RESTORE DATABASE commands, but I have found the following difficulties:
They require me to specify the name of the database. Is there a way how to default them to the initial database specified as part of the connection string?
The RESTORE DATABASE command contains names and paths of the respective data files on the disc (MOVE parts). Is there a way how to process it with specifying just the database name without providing the data files path? Or how to get the data files paths via SQL commands (to get the file names, I will just create a blank database, got the file names, optionally drop the database and use the retrieved file names)?
Is there a better way doing this?
I use a stored procedure i created, but first you need to create a linked server:
IF EXISTS(SELECT name FROM sys.servers WHERE name = 'SERVER')
BEGIN--
EXEC sp_dropserver 'SERVER', 'droplogins'
END
/****** Object: LinkedServer [SERVER] create LinkedServer ******/
EXEC master.dbo.sp_addlinkedserver
#server = N'SERVER',
#srvproduct=N'SQLNCLI',
#provider=N'SQLNCLI',
#datasrc=N'192.168.1.1' -- IP address of a server
/* Add login data*/
EXEC sp_addlinkedsrvlogin
#useself='FALSE',
#rmtsrvname='SERVER',
#rmtuser='User',
#rmtpassword='Pass'
Then you can create stored procedure on local server or execute the query directly from application, also for safety I am using a transaction in this example:
USE [DB]
GO
/****** Object: StoredProcedure [dbo].[backupdatabase] ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[backupdatabase]
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
BEGIN TRY
BEGIN TRANSACTION
TRUNCATE TABLE [dbo].[table_1]
INSERT INTO [dbo].[table_1]
SELECT * FROM [SERVER].[DB].[dbo].[table_1]
TRUNCATE TABLE [dbo].[table_2]
INSERT INTO [dbo].[table_2]
SELECT * FROM [SERVER].[DB].[dbo].[table_2]
TRUNCATE TABLE [dbo].[table_3]
INSERT INTO [dbo].[table_3]
SELECT * FROM [SERVER].[DB].[dbo].[table_3]
COMMIT
END TRY
BEGIN CATCH
IF ##TRANCOUNT > 0
BEGIN
ROLLBACK TRANSACTION
DECLARE #ErrMsg nvarchar(4000), #ErrSeverity int
SELECT #ErrMsg = ERROR_MESSAGE(),
#ErrSeverity = ERROR_SEVERITY()
RAISERROR(#ErrMsg, #ErrSeverity, 1)
END
END CATCH
END

Connecting to server vs connecting to database

What's the difference between connecting to a server as opposed to connecting to a database?
The context of the question is that I'm in charge of developing a proof of concept where a user can select one of our servers, a database within that server, a table within that database, and a column within that table. I am using Visual C# and ASP.NET. I believe I can get the servers from the connection strings in the web.config, but I'm not quite sure how.
If it helps at all (I do like examples), you can assume SQL servers.
(Answer to original question)
There is a hierarchy:
Server: A piece of physical (or virtual) hardware that runs an OS and applications. You will address it via IP address or DNS name, in can host multiple Database Servers
Database Server (aka Instance): A piece of software that runs that can host multiple Databases. when you use a connection string it is in the format "ServerName\InstanceName"
Database: A data structure that can host multiple Data Tables
Data Table: A data structure that can host multiple Columns and Rows
Column: The smallest division of information seperation, holds information about a specific topic
Row: Holds a single set of columns.
(Answer to updated question)
It is different per SQL provider, but using Microsleft SQL server you just connect to the server (don't provide a default instance in the connection string) and do the following:
select * from sys.databases
Once you have your database, connect to that database and do the following to get the tables
select * from sys.tables where type = 'U'
to get the columns you do
select * from sys.Columns
however to get the name of the table the column is in you need to match Object_id to Object_id on sys.tables
select t.name as TableName, c.Name as ColumnName
from sys.tables t
inner join sys.columns c on t.object_id = c.object_id
where t.Type = 'U'
You can achieve your goal. Initially, you would connect to database master on the server and query the databases on that server.
SELECT * FROM sys.databases
Then, you would initiate a new connection to the selected database and query that database's information schema, to get a list of tables.
SELECT * FROM INFORMATION_SCHEMA.TABLES
Repeat for selecting a column.
SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'foo'
If by server you mean database server, you would connect to the server to gain access to the database hosted on that server.

Pull Data off of Remote Server into Local Server ... Best, Most Secure Way

I have a online signup that saves data onto a hosted mssql database ... Essentially what i'm trying to do is as have a daily routine run on the local server as simple as
Insert into Home.tableA Select * from Remote.tableA Where Date = Today
However, this will not work ... what would be the best way to accomplish this either in T-SQL or C# ...
Thanks for the Insight
option 1. You can setup table replication
option 2. You can get Home.TableA Max(Id) and insert rows from Remote.TableA where Remote.TableA.ID > Home.TableA Max(Id).
option 3. Setup another table to keep the MAX(Id) and datetime the job run.

SQL Server 2000 - Programmatically Limit Access to Database Owner?

How would I programmatically go about limiting the access of a database in SQL Server 2000 to the database owner for that database? Example... if I right-click "Properties" on the "Northwind" database in Enterprise Manager, the Owner is listed as sa. How would I limit access for this database to just the sa login?
You could set the database to RESTRICTED_USER availability.
ALTER DATABASE MyDatabase SET RESTRICTED_USER
-- OR --
ALTER DATABASE MyDatabase SET RESTRICTED_USER WITH ROLLBACK IMMEDIATE
http://msdn.microsoft.com/en-us/library/ms190249.aspx
http://msdn.microsoft.com/en-us/library/aa275464(SQL.80).aspx
Some thoughts:
You can neither deny not restrict the sa login at all, anywhere in a SQL Server Instance
Do not use "sa" day to day
It makes more sense to limit to the members of the db_owner database role, per database (SET RESTRICTED_USER above)
The database owner id is fairly random: sa only owns this because sa created it, or ownership was changed to sa
Other than that, what is the reasoning behind your request?

Categories