I have a SQL 2008 database that is stored on the same instance, but this database is created by the user and name is stored in SQL table. How do I write a select statement using dynamic sql or is there a another way
So for example:
Main database - myDB
User database - userDB (this is stored in a myDB.dbo.tblUserDatabase)
userDB has a table called tblUserReports
I want to write something like this in dynamic sql:
SELECT * FROM userDB.dbo.tblUserReports
So tried:
declare #dbUser varchar(50)
set #dbUser = (SELECT strDBName FROM myDB.dbo.tblUserDatabase)
SELECT * FROM #dbUser.dbo.tblUserReports
You can do this... dynamic sql can become unmanageable very quickly so be careful.
declare #dbUser varchar(50)
set #dbUser = (SELECT strDBName FROM myDB.dbo.tblUserDatabase)
DECLARE #sql NVARCHAR(1000)
SET #sql = 'SELECT * FROM ' + QUOTENAME(#dbUser) + '.dbo.tblUserReports'
EXEC sp_executesql #sql
You cannot parameterise the table name. You will have to use dynamic SQL in your client or stored procedures. It's a very unusual thing to want to do so think long & hard about if this is a good design. Maybe if you share what you are doing then you'll get some additional ideas as to how to approach your problem.
Related
I need to TRIM databases as per requirement. So, I'm using below script and giving database names manually. All I need is to automate the script to get database names automatically. Can anyone please suggest how to get the database name automatically.
Use [Sales_backup_2015_05_31_230001_7137975]
Exec [spMaint_TrimTestDB] 1
Go
for Eg:
instead of giving manually Sales_backup_2015_05_31_230001_7137975 I need to get db name automatically
Thanks.
There is a function DB_NAME() that would return the name of the current database if no parameters are passed. Check this.
I guess dynamic SQL might help you to run SP in different databases:
DECLARE #sql nvarchar(max)
SELECT #sql = (
SELECT N'Use '+QUOTENAME([name]) +' Exec [spMaint_TrimTestDB] 1;'
FROM sys.databases
WHERE database_id >= 5 AND [name] like 'Sales_backup%'
FOR XML PATH('')
)
EXEC sp_executesql #sql
This script will create and execute dynamic statement like:
Use [sales_backup_2015] Exec [spMaint_TrimTestDB] 1;
Use [sales_backup_2016] Exec [spMaint_TrimTestDB] 1;
etc...
Observe the following simple SQL code:
CREATE TABLE #tmp (...) -- Here comes the schema
INSERT INTO #tmp
EXEC(#Sql) -- The #Sql is a dynamic query generating result with a known schema
All is good, because we know the schema of the result produced by #Sql.
But what if the schema is unknown? In this case I use Powershell to generate a Sql query like that:
SET #Sql = '
SELECT *
INTO ##MySpecialAndUniquelyNamedGlobalTempTable
FROM ($Query) x
'
EXEC(#Sql)
(I omit some details, but the "spirit" of the code is preserved)
And it works fine, except that there is a severe limitation to what $Query can be - it must be a single SELECT statement.
This is not very good for me, I would like to be able to run any Sql script like that. The problem, is that no longer can I concatenate it to FROM (, it must be executed by EXEC or sp_executesql. But then I have no idea how to collect the results into a table, because I have no idea of the schema of that table.
Is it possible in Sql Server 2012?
Motivation: We have many QA databases across different Sql servers and more often than not I find myself running queries on all of them in order to locate the database most likely to yield best results for my tests. Alas, I am only able to run single SELECT statements, which is inconvenient.
We use SP and OPENROWSET for this purpose.
At first create SP based on a query you need, than use OPENROWSET to get data into temp table:
USE Test
DECLARE #sql nvarchar(max),
#query nvarchar(max)
SET #sql = N'Some query'
IF OBJECT_ID(N'SomeSPname') IS NOT NULL DROP PROCEDURE SomeSPname
SET #query =N'
CREATE PROCEDURE SomeSPname
AS
BEGIN
'+#sql+'
END'
EXEC sp_executesql #query
USE tempdb
IF OBJECT_ID(N'#temp') IS NOT NULL DROP TABLE #temp
SELECT *
INTO #temp
FROM OPENROWSET(
'SQLNCLI',
'Server=SERVER\INSTANCE;Database=Test;Trusted_Connection=yes;',
'EXEC dbo.SomeSPname')
SELECT *
FROM #temp
I am preparing a group of sql queries for a dashboard. I want to declare the database name at the beginning so that the queries will work on the database specified on top without making any changes in the underlying code
Original query:
SELECT *
FROM Check.dbo.Dates_table
The query I want:
DECLARE #Databasename VARCHAR(200)
SET #Databasename = 'Check.dbo'
SELECT * FROM #Databasename.Dates_table
You can use "USE" operator: https://msdn.microsoft.com/en-AU/library/ms188366.aspx
use Check
SELECT * FROM dbo.Dates_table
I would like to split my database into two databases, a quick check showed that I can easily query, join, update tables across databases.
My main problem now is that to do this, I will have to do something like this.
SELECT *
FROM Database1.dbo.Table1,
Database2.dbo.Table2
As you can see I have to explicit mentioned database names, which means that if database name is deployed with a different name, this code will not work anymore.
Any ideas to overcome this problem?
You can use db_name() to get the current database name and dynamic sql to build a dynamic query.
Something like:
declare #databaseName nvarchar(max) = db_name()
declare #dynamicSql nvarchar(max) = 'SELECT * FROM '+ #databaseName + '.dbo.Table1'
exec sp_executesql #dynamicSql
I manage a server with around 400+ databases which have the same database schema, i wish to deploy a custom clr/.net user defined function to them all, is there any easy way to do this, or must it be done individually to each database?
Best Regards,
Wayne
I think if you create it in master (in MSSQL) it can be referenced from any other db in that instance. Certainly seems to work for Stored Procs anyway.
I should add that this only works if the databases are all on the same server instance...
You could write a small app to deploy the udf to the master of each SQL server instance if all 400 reside on multiple servers.
I just find some way i think. Some kind of Inception ;)
USE data_base works only inner EXECUTE context, so...
DECLARE #sql NVARCHAR(max)
DECLARE #innersql NVARCHAR(max)
DECLARE c CURSOR READ_ONLY
FOR
SELECT name FROM sys.databases
DECLARE #name nvarchar(1000)
OPEN c
SET #innersql = 'CREATE FUNCTION Foo(#x varchar(1)) RETURNS varchar(100) AS ' +
' BEGIN RETURN(#x + ''''some text'''') END;'
-- ^^^^ ^^^^
-- every (') must be converted to QUAD ('''') instead of DOUBLE('') !!!
FETCH NEXT FROM c INTO #name
WHILE ##FETCH_STATUS = 0
BEGIN
-- create function must be the first statement in a query batch ???
-- ok, will be... in inner EXEC...
SET #sql = 'USE [' + #name + ']; EXEC (''' + #innersql + ''');'
--PRINT #sql
EXEC (#sql)
FETCH NEXT FROM c INTO #name
END
CLOSE c
DEALLOCATE c
Ups, I missed "CLR/.NET" part reading question. Sorry.
i'd just create a dynamic script to create it on each database. but after that i'd put it in the modal databases so that all new databases are created with it.
you could also use the same script to push out changes if the function ever gets modified.