TSQL: variable for access to database (SQL Server 2008) - sql-server-2008

I have written a T-SQL script that migrates some data from one database to another.
At the moment I am doing that by use of dynamic sql.
For example see the following code:
Declare #sqlquery nvarchar(4000)
SET #sqlquery = N'SELECT * from ' + #LinkServerName + #SourceDatabaseName + '.dbo.Table'
EXEC #sqlquery
In this example #LinkServerName is a nvarchar variable that stores the name of the linked server for the SQL Server that contains the source database. #SourceDatabaseName is a nvarchar variable that stores the name of the source database.
I donĀ“t like that way. I would prefer the following code:
SELECT * from #SourceDatabase.dbo.Table
Is that possible?
Thank you in advance.

Second approach is incorrect, first one is the correct one. For more information check this other question here at stackoverflow how-to-use-variable-for-database-name-in-t-sql

Related

SSIS Using Variables in Query Name

Let's say I have the following scenario
Select
age
,address
,full_name
from
[dbo].customers
I want to replace the [dbo] part with an ssis variable, so when we go to run this package and need to replace the schema, it's a piece of cake.
What I have tried so far was creating a SQL variable, named schema_var_name, and appending it to the front, but this is not working out for me.
Can you tell me what I am doing wrong?
Here is what I have:
"Select
age
,address
,full_name
from
'#[User::schema_var_name]' + '.[customers]' "
You will need to concatenate the #[User::schema_var_name] variable within the SQL text, with the other parts of the query enclosed with double-quotes ("). An example of an expression for your SQL command is below. This can then be used as the expression for a variable that is set for the source statement in an Execute SQL Task or source component within a Data Flow Task.
"Select age, address, full_name from " + #[User::schema_var_name] + ".[customers]"
You could also build a dynamic sql statement and execute it in an Execute SQL Task. The ? tells the task that you want to use a variable in that location. You then set up the variable under Parameter Mapping. Your query would then look like this:
DECLARE #schemaName NVARCHAR(100) = ?
DECLARE #sqlQuery NVARCHAR(MAX) = N'
SELECT
age
,address
,full_name
FROM
[' + #schemaName + '].customers'
EXEC(#sqlQuery)
EDIT:
Here's what the Parameter Mapping would look like:
The Parameter Name is most often the least intuitive of these fields. It's a 1-based id sequence for Input parameters. If you had another input variable to use, its Parameter Name would be 2.

MS SQL Linked Servers And Using In FROM Clause

I have a very basic test stored procedure, shown below. This proc is reading data in a different database, in a different server. To do this I am using a linked server. From what I have read, I need to change the FROM clause to this:
[linked server name].[database name].[schema name].[table name]
However, I would like to pass in the linked server name and database name as parameters and use them in my FROM clause. I am not concerned with injection attacks, etc. I will be passing this in from a config file.
create PROC [dbo].[SelectTEST]
#GU UNIQUEIDENTIFIER,
#LINKED_SERVER_NAME nvarchar(max),
#DATABASE_NAME nvarchar(max)
AS
SET NOCOUNT ON
SET XACT_ABORT ON
BEGIN TRAN
SELECT [GU]
FROM '[' + #LINKED_SERVER_NAME +'].['+ #DATABASE_NAME + '].[Test Table] '
WHERE ([GU] = #GU OR #GU IS NULL)
COMMIT
This is a big mess of syntax errors. Is it possible to pass in these parameters and use in my stored procedure? I would have to make this change to a bunch of different procs, so sorta trying to find the a succinct solution...

Variables not recognized in an Execute SQL task

I have this sql statements running in my ssis package. I have hard coded the email address. How can i pass it as variable and externalize the variable and can pass the value from config file?
The #PackageStartTime is the system start time. I have declared that variable and set the expression in property window with #[System::StartTime] and evaluated that expression. But when i run this package and when it hits this particular task it get stuck at there saying PackageStartTime parameter is not recognized and result property is not set correctly.
Here is my code:
DECLARE #PackageStartTime Varchar(250)
SET #PackageStartTime =?
IF (SELECT COUNT(*) FROM [dbo].[Table1] WHERE RowCDate >= #PackageStartTime) > 0
BEGIN
DECLARE #SUB Varchar(250)
SET #SUB = 'File Failed' + ##SERVERNAME
DECLARE #BODY Varchar(250)
SET #BODY = 'File Failed' + ##SERVERNAME
EXEC msdb.dbo.sp_send_dbmail
#profile_name='default',
#recipients='dev#null.com',
#subject=#SUB,
#body=#BODY,
#query= 'SELECT DISTINCT FileLoadName FROM [dbo].[Table1] WHERE RowCDate >= #PackageStartTime',
#attach_query_result_as_file=1
Any idea what to solve these two things?
Thanks in advance.
Maina, I just responded to your another post on this subject. You have three posts so far that I have encountered. The questions you have asked in this one are very general in nature and the answer can be found in any good book (such as Professional Microsoft SQL Server 2008 Integration Services). You can also find complete step-by-step answer on many websites (but do not use them as a replacement of a book; otherwise chances are your knowledge of SSIS will remain patchy.
With that said, here are two links that answer your questions:
1. Passing a variable: https://www.simple-talk.com/sql/ssis/passing-variables-to-and-from-an-ssis-task/ (Actually, it appears I had sent this link to you earlier as well.)
Assigning variable values from config - http://www.bidn.com/blogs/DevinKnight/ssis/1655/passing-values-into-an-ssis-package-at-runtime-from-outside-the-package
Focus on item 1 first. After you have practiced it, create a new Execute sql task and put just his much code inside it:
DECLARE #PackageStartTime Varchar(40)=?;
SELECT COUNT(*) FROM [dbo].[Table1] WHERE RowCDate >= #PackageStartTime;
and store this row count in a package variable iCount. Returning the value is done through ResultSet property. If you are able to make this task work, you have enhanced your proficiency in Execute SQL Task.

SQL Server 2008 get data from unified tables

I've a stored proc like:
CREATE PROCEDURE [dbo].[GetData]
#code varchar(10)
AS
BEGIN
SET NOCOUNT ON;
--code goes here
END
the proc reads data from one of n tables, based on #code passed. So I've a map linking codes with the actual table names, ex.
Code:"A" => dbo.JAN_SALES
Code:"B"=> dbo.FEB_SALES
All tables have the same structure. I know how to get it done by using 'red' sql, wonder if there's more elegant/performant way of doing that with SQL Server 2008?
Edit 1 - Red sql is the sql, which gets built by concatenating its parts and executed by calling something like exec('select A. B, C from ' + #myTable).
Your question seems to be clear on what needs to be done, and there are no much more posibilities than creating the T-SQL code by
1) adding IF blocks evaluating the #code parameter; or
2) using Dynamic Sql ( dynamic sql = "red" ). Please note the dynamic sql is strongly discouraged for production environments.
BTW - On SQL Server 2008 you can use *sp_executesql* proprietary stored procedure. Microsoft's MSDN describes how it works here.

Delete all procedures except those which contain a string in their name

I want to drop a lot of SPs from my SQL Server database. However, I want to write "Delete all procedures except those which contain a certain string in their name".
How can I do this? I am using SQL Server 2008 R2.
Thank
What about:
SELECT 'DROP PROCEDURE ' + name
FROM sysobjects WHERE xtype = 'U' AND
name LIKE 'usp_%' -- Here you'll define your criteria
After running this, you just need to execute this command output.