I want to get a list of tables exist in another database. for example if i have connected DB1 database and i want to get a list of tables from DB2 then how is it possible?
I know there are some another approaches like connect DB2 and execute insert query to insert schema into #temp table then connect DB1 using USE [DB1] statement and use that #temp table.
But, I don't want to change my sql connection at runtime. Because, there are some dependencies i have created on my sql connection.
UPDATED:
Database can be restored in same server. Now i am using following query to get Table List from the database.
SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE='BASE TABLE'
version of sql server is 2005.
You need sp_addlinkedserver()
http://msdn.microsoft.com/en-us/library/ms190479.aspx
Example:
exec sp_addlinkedserver #server = 'test'
then
select * from [server].[database].[schema].[table]
Copy Table Schema and Data From One Database to Another Database in SQL Server
Remus Rusanu has already mentioned Here
Try this Query
declare #sql nvarchar(max);
set #sql = N'select cast(''master'' as sysname) as db_name, name collate Latin1_General_CI_AI, object_id, schema_id, cast(1 as int) as database_id from master.sys.tables ';
select #sql = #sql + N' union all select ' + quotename(name,'''')+ ', name collate Latin1_General_CI_AI, object_id, schema_id, ' + cast(database_id as nvarchar(10)) + N' from ' + quotename(name) + N'.sys.tables'
from sys.databases where database_id > 1
and state = 0
and user_access = 0;
exec sp_executesql #sql;
I assume that you've set the database in your connection string.
If the other database is on the same server, you can reference them with a three-part name
select * from otherdb.schema.table
If it's not, you can use a four-part name
select * from otherserver.otherdb.schema.table
But my advice would be to not do that directly but rather create a synonym for each object that you plan to reference externally.
That way you gain some flexibility if you do something like rename the external database.
Related
Using what's available in the System.Data.SQLite namespace and using C# I'm doing database operations. However, there is one problem I can't seem to get figured out.
If I want to create a table which is NAMED DYNAMICALLY AT CREATION, I thought the way to do that would be ...
command.CommandText = #"CREATE TABLE IF NOT EXISTS #tableName( ... )";
and then do this ...
command.Parameters.AddWithValue("#tableName", tableName);
and then do the
command.ExecuteNonQuery();
But what's happening is that I'm getting a new table named "#tableName" instead of whatever the variable tableName is set to.
How can I get this to work correctly?
The way that I approach problems like this is to simplify as much as I can. In this case, simple string substitution should easily resolve your problem without the need to use parameters.
For example:
command.Text = $#"CREATE TABLE IF NOT EXISTS {tableName}( ... )";
or
command.Text = string.Format(#"CREATE TABLE IF NOT EXISTS {0}( ... )", tableName);
Can you create procedure instead of inline query . you can manage easy in stored procedure like this .`CREATE PROCEDURE Dynamic_SP
#Table_Name sysname AS BEGIN
SET NOCOUNT ON;
DECLARE #DynamicSQL nvarchar(4000)
SET #DynamicSQL = N'SELECT * FROM ' + #Table_Name
EXECUTE sp_executesql #DynamicSQL END
I have an Azure SQL database that contains two tables Product and Order that are saved in the dbo schema. I want to write a C# program that will add new schema and duplicate the same tables definition that exist in dbo.
Existing:
dbo.Product
dbo.Order
Run the C# program to create a new schema for client1 then two tables will be added to the data base and the list of tables become:
dbo.Product
dbo.Order
client1.Product
client1.Order
Would you please let me know how I can do that with c#?
You can create a stored procedure that receives two input parameters:
name of the schema to be duplicated
name of the new schema
Then you can invoke this procedure from your c# program.
Inside the procedure you can build a dynamic statement querying SQLServer's system table INFORMATION_SCHEMA.TABLES.
The idea is to:
create the new schema
clone source tables from the old schema to the new schema
then delete all rows from the tables in the new schema
Please not that if you have foreign keys you'll have to manage them.
Here is a sample to start from:
create procedure p_clone_schema(
#source_schema nvarchar(50),
#new_schema nvarchar(50)
)as
begin
--check if destination schema already exists
if not exists (select * from INFORMATION_SCHEMA.SCHEMATA where schema_name = #new_schema)
begin
--create new schema
declare #sql nvarchar(max) = 'CREATE SCHEMA ' + QUOTENAME(#new_schema)
exec(#sql)
set #sql = ''
--build statement to copy tables in the new shema and then truncate them
select #sql = CONCAT
(
#sql , 'select * into ' , QUOTENAME(#new_schema) , '.' , QUOTENAME(TABLE_NAME)
, ' from ' , QUOTENAME(TABLE_SCHEMA) , '.' , QUOTENAME(TABLE_NAME)
, ' truncate table ' , QUOTENAME(#new_schema) , '.' , QUOTENAME(TABLE_NAME)
)
from INFORMATION_SCHEMA.TABLES
where TABLE_SCHEMA = #source_schema
and TABLE_TYPE = 'BASE TABLE'
exec(#sql)
end
end
I want to add one column to an existing table in C#, if it doesn't already exist. I know I have to use an 'alter table' command.
But I am not able to fire that command in my C# code.
How can I do?
I'm using Visual Studio 2010 and Sql Server 2008.
this :
Use [DatabaseName]
Go
if Not exists( Select * from sys.columns As clm
where clm.object_id = OBJECT_ID(N'[TableName]')
And clm.name = N'[ColumnName]'
)
Begin
Alter Table TableName
Add ColumnName DataTypeName
End
I'm developing an windows application using MySQL as data-base server.
I need to execute a prepared statement and want to load result into data-set without using stored procedure.
Can any one tell me how can i do this.
Statement
SET #Statment =
(
SELECT REPLACE(
REPLACE(
GROUP_CONCAT(
Concat(' SELECT COUNT(*) AS `ROWS`//''',TABLE_NAME,''' AS `TABLE` FROM ', TABLE_NAME , ' UNION ALL')
)
,',','')
,'//',',')
FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'wbss'
);
SET #Statment = (SELECT SUBSTRING(#Statment,1,LENGTH(#Statment) - 9));
PREPARE STMT FROM #Statment;
EXECUTE STMT;
DEALLOCATE PREPARE STMT;
Note:- I'm not having permission to do this using stored procedure.
Have you tried passing these queries as a parameter for MYSql command?try concatenating them and passing as single string. try with hard coded values to begin with.
I don't want to tell you the exact solution but may be something like this:
cmd.CommandText = "insert into animals (id, name) values (:id, :name);+
select id, name from animals where id = last_insert_id()";
Please do not consider it a literal solution.Consider it an option and make your way through it.
I have a System that fetches its data from different DBs on the same server.This DBs are newly attached to the server annually.e.g. at the at the beginning of 2013, a db called 2012 is attached.
So I want to create a stored procedure(SP) that fetches the user's input which can be anything from 2005(year). so based on the year the user enters, the SP should go to that db(whose name will be the year the user entered) and search for the data (with its parameter being the year the user entered) inside the db which will also has a table with the same name as the db(i.e the table will have the same name as the year name).
Hope this makes sense
It would be a good idea to paramatarize the query.
e.g.
CREATE PROC usp_bar
(
#ID INT
)
AS
BEGIN
DECLARE #SQL NVARCHAR(100)
DECLARE #Params NVARCHAR(100)
SET #SQL = N'SELECT * FROM [Table] WHERE ID = #ID'
SET #Params = N'#ID INT'
EXEC sp_executesql #SQL, #Params, #ID = 5
END
Check out this
I am no DBA so take this with a grain of salt and understand there may be a better way to do this but what you will probably have to do is something like this:
CREATE PROCEDURE usp_foo
#Year varchar(4)
AS
DECLARE #sql varchar(255)
#sql = 'SELECT * from [' + #Year + '].[owner].[table]'
sp_executesql #sql
Of course the user calling this sproc will have to A) have permissions to call system sprocs B) have permission to access the yearly database
Additionally, instead of going the SQL route, you could just make a dynamic connection string that you could populate with the correct catalog then issue your SQL queries directly to the database. Personally I would prefer that over using dynamic SQL.
One thing you could do, is take a look at synonyms, you could create one for each year:
http://sommarskog.se/dynamic_sql.html#Dyn_DB
CREATE SYNONYM otherdbtbl FOR otherdb.dbo.tbl
I'd recommend his site, it's full of good stuff, it's a great read :)
As to whether this works well for you, I'd expect it depends on how many tables you have in each DB. If it's a few this may work, if it's hundreds maybe another approach may work better - like abszero's suggestion of doing the switching in the application tier?