Execute SSIS package and set package parameters in catalog - sql-server

I have created a stored procedure to execute an ssis package in the catalog and set the package parameters dynamically at run time. I then create a job step to use the Operating system (CMDEXEC) Command to run the dtexec utility. The code is below:
ALTER PROCEDURE [Administration].[prc_Exec_LoadbenefitStatement_SSIS_TEST1]
#Destination varchar(250),
#FinancialFile varchar(250),
#StaticFile varchar(250),
#StatementType varchar(15),
#ExternalID varchar(20),
#SourceSystemID varchar(20)
AS
DECLARE #jid as uniqueidentifier
BEGIN TRANSACTION
SET NOCOUNT ON;
DECLARE #statement varchar(2000)
BEGIN
SET #statement = 'dtexec /ISServer "\SSISBD\AFFS\KhanyaStatements\Khanya_LoadBenefitStatement.dtsx" /SERVER "XXXXX\SQL01"'
SET #statement = #Statement + ' /Par "Destination";' + #Destination
SET #statement = #Statement + ' /Par "FinancialFile";' + #FinancialFile
SET #statement = #Statement + ' /Par "StaticFile";' + #StaticFile
SET #statement = #Statement + ' /Par "StatementType";' + #StatementType
SET #statement = #Statement + ' /Par "ExternalID";' + #ExternalID
SET #statement = #Statement + ' /Par "SourceSystemID";' + #SourceSystemID
END
DECLARE #jname varchar(128)
SET #jname = cast(newid() as char(36))
EXEC msdb.dbo.sp_add_job
#job_name = #jname,
#enabled = 1,
#category_name = 'KhanyaStatements_SSIS',
#delete_level = 3,
#job_id = #jid OUTPUT
EXEC msdb.dbo.sp_add_jobserver
#job_id = #jid,
#server_name = 'XXXXX\SQL01'
EXEC msdb.dbo.sp_add_jobstep
#job_id = #jid,
#step_name = 'Execute SSIS',
#subsystem = 'CMDEXEC',
#proxy_name = 'pr_KhanyaStatements',
#command = #statement
DECLARE #returncode tinyint
EXEC #returncode = msdb.dbo.sp_start_job
#job_id = #jid
SELECT #returncode
SET NOCOUNT OFF;
COMMIT TRANSACTION
I have created the Credential, Proxy and Job Category. When I execute the proc the return code is 0 for success but I can clearly see that the package did not execute. Please assist?

Related

Must declare variable

I have an error during the execution of my proc that I must declare my variable while this last variable is well declared
because I declared my variables in the proc
Proc Syntax
USE [Test]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[ADMIN_D] #LNK_Name nvarchar(60) ,#bdd varchar(50) ,#PS VARCHAR(80), #SCH SYSNAME = 'dbo'
AS
Declare #sqlm varchar(max)
Declare #sql1 nvarchar(max)
Declare #sql nvarchar(max)
Declare #sqlZ varchar(max)
Declare #LINK nvarchar(max)
Declare #LINK1 nvarchar(max)
Declare #LINK2 varchar(max)
--Declare #bdd varchar(35)
Declare #Login varchar(80)
Declare #Datetime datetime
SET NOCOUNT ON;
IF (ORIGINAL_LOGIN() IN (''))
BEGIN;
PRINT 'Déploiement interdit - Contactez l''équipe SQL ';
RETURN;
END;
SET #Datetime = Getdate()
SET #Login = system_user
SELECT #sql = Definition
FROM sys.procedures p
INNER JOIN sys.sql_modules m ON p.object_id = m.object_id
where name = #PS and p.schema_id = SCHEMA_ID(#SCH)
--BEGIN DISTRIBUTED TRAN
raiserror('--- Alim Z_CODESOURCE de Prod',0,1) WITH NOWAIT
SET #sqlZ = 'EXEC dbo.Z_CODESOURCE_Alim #NOM_OBJET = ''' + #PS + ''''
SET #LINK = N'EXEC (#sqlZ) AT ' + QUOTENAME(#LNK_Name);;
EXEC sp_executesql #LINK;
SET NOCOUNT OFF
IF EXISTS (SELECT TOP 1 1 FROM ADMIN_DEPLOY_BLOCK WHERE NOM_PS = #PS AND Nom_Schema = #SCH)
BEGIN
SELECT 'DEPLOIEMENT INTERDIT PAR ' + ACTEUR + '. RAISON: ' + RAISON
FROM ADMIN_DEPLOY_BLOCK
WHERE NOM_PS = #PS
AND Nom_Schema = #SCH;
PRINT 'Pas de déploiement !'
END
ELSE
BEGIN TRY
SET #sqlm = ' USE [' + #bdd + '];DELETE FROM METADATA WHERE NAME = '''+#PS+''''
SET #LINK = N'EXEC (#sqlm) AT ' + QUOTENAME(#LNK_Name);
EXEC sp_executesql #LINK ;
SET #sql1 = 'IF EXISTS (SELECT * FROM sys.objects WHERE type IN (''P'', ''FN'') AND name = '''+#PS+''' AND schema_id = ( select schema_id from sys.schemas WHERE name=''' + #SCH + ''' )) DROP PROCEDURE ' + #SCH + '.' + #PS
SET #sql1 = 'IF EXISTS (SELECT * FROM sys.objects WHERE type IN (''P'', ''FN'') AND name = '''+#PS+''') DROP PROCEDURE '+#PS
SET #sql1 = REPLACE(#sql1,'''','''''')
SET #sql1 = 'USE [' + #bdd + ']; EXEC(''' + #sql1 + ''')'
SET #LINK1 = N'EXEC (#sql1) AT ' + QUOTENAME(#LNK_Name) ;
EXEC sp_executesql #LINK1 ;
SET #sql = REPLACE(#sql,'''','''''')
SET #sql = 'USE [' + #bdd + ']; EXEC(''' + #sql + ''')'
SET #LINK2 = N'EXEC (#sql) AT ' + QUOTENAME(#LNK_Name) ;
EXEC sp_executesql #LINK2 ;
INSERT INTO LOG_DEPLOYPS (LOGIN, PS, DAT) values (#login, #PS, #datetime)
Print ''
Print ''
Print 'Déploiement effectuée avec succès'
--COMMIT TRAN
END TRY
BEGIN CATCH
Print ''
Print ''
Print 'Une erreur est survenue: ' + CAST(##ERROR AS VARCHAR(255))
SELECT
#PS AS ProcedureName
,ERROR_NUMBER() AS ErrorNumber
,ERROR_SEVERITY() AS ErrorSeverity
,ERROR_STATE() AS ErrorState
,ERROR_PROCEDURE() AS ErrorProcedure
,ERROR_LINE() AS ErrorLine
,ERROR_MESSAGE() AS ErrorMessage;
--ROLLBACK TRAN
END CATCH
END
Execute Proc
USE [Test]
GO
DECLARE #return_value int
EXEC #return_value = [dbo].[ADMIN_D]
#bdd = N'PROD',
#PS = N'SP_login',
#LNK_Name=N'uat-link'
SELECT 'Return Value' = #return_value
GO
Someone who can help me please
enter image description here
Run stored procedure on linked server (linked server name as variable)
The problem is these lines (and other places later on where you use the same pattern):
SET #LINK = N'EXEC (#sqlZ) AT ' + QUOTENAME(#LNK_Name);;
EXEC sp_executesql #LINK;
The sp_executesql function creates a new execution context that doesn't know about the #sqlZ variable. To get around this, there are additional arguments you must pass to the function to set up the variables and their values.

SQL Server incorrect syntax exception when executing with sp_executesql

I am calling a procedure from a trigger and passing some parameters from trigger to procedure. Parameters are:
#table_name varchar(128), #where_str varchar(200)
Inside the procedure, I'm executing a command with sp_executesql. I think, I am using incorrect syntax, but I couldn't find the resolution.
This is the executed query:
SET #SqlString = N'update #ptable_name set RepSt=2 #pwhere_str';
SET #ParmDefinition = N'#ptable_name varchar(128), #pwhere_str varchar(200)';
execute sp_executesql #SqlString, #ParmDefinition,
#ptable_name = #table_name, #pwhere_str = #where_str;
Passed parameters are like that:
#table_name is [MyTable]
#where_str = N'where MyColumnA = '+#oldMyColumnA+N' AND MyColumnB = '+#oldMyColumnB+N' AND MyColumnC = '+#oldMyColumnC;
What you end up executing is something like:
DECLARE #ptable_name VARCHAR(128) = 'your_Table'
, #pwhere_str VARCHAR(200) = 'Your_where_clause'
UPDATE #ptable_name
SET RepSt=2
WHERE #pwhere_str
This doesn't work, you need to replace the variable in the executed sql:
SET #SqlString = N'update #ptable_name set RepSt=2 #pwhere_str';
SET #SqlString = REPLACE(REPLACE(#SqlString, '#ptable_name', #table_name), '#pwhere_str', #where_str)
execute sp_executesql #SqlString
(Very dirty, but this is the idea.)
SET #SqlString =N'update ' + #ptable_name + ' set RepSt=2 #pwhere_str';

How to create the date wise backup file using T-SQL script

I wrote the following script but it shows an error due to the + sign in #command argument. Could anyone suggest how I can get rid of this error?
USE msdb;
GO
--add a job
EXEC dbo.sp_add_job
#job_name = N'FullBackup';
GO
USE msdb;
GO
--add jobsteps to jobsteps
DECLARE #fileName VARCHAR(90);
DECLARE #db_name VARCHAR(20);
DECLARE #fileDate VARCHAR(20);
DECLARE #commandtxt VARCHAR(100);
SET #fileName = 'D:\SQL server\BackUp\';
--SET #db_name = 'AdventureWorks_';
SET #fileDate = CONVERT(VARCHAR(8), GETDATE(),112);
SET #fileName = #fileName + #db_name + RTRIM(#fileDate) + '.bak';
SET #commandtxt = N'''BACKUP DATABASE [AdventureWorks2012] TO DISK =N''' + #fileName + ''' WITH INIT';
EXEC sp_add_jobstep
#job_name = N'FullBackup',
#step_name = N'Weekly Full Backup',
#subsystem = N'TSQL',
#command = 'BACKUP DATABASE [AdventureWorks2012] TO DISK =N''' + #fileName + ''' WITH INIT',
#retry_attempts = 5,
#retry_interval = 5;
GO
--Create a Schedule for this job, backup, occurs once a week each friday at 11:59
EXEC sp_add_schedule
#schedule_name = N'WeeklyBackup1',
#freq_type = 8,
#freq_interval = 32,
#freq_recurrence_factor = 1,
#active_start_time = 235900;
GO
--attach the schedule to the job
EXEC sp_attach_schedule
#job_name = N'FullBackup',
#schedule_name = N'WeeklyBackup1';
GO
EXEC dbo.sp_add_jobserver
#job_name = N'FullBackup';
GO
Try this
SET #commandtxt = N'BACKUP DATABASE [AdventureWorks2012] TO DISK =N''' + #fileName + ''' WITH INIT'
EXEC sp_add_jobstep
#job_name = N'FullBackup',
#step_name = N'Weekly Full Backup',
#subsystem = N'TSQL',
#command = #Commandtxt,
#retry_attempts = 5,
#retry_interval = 5;
GO
.
.
.

job schedule to a SQL Job

How do I schedule a job using sp_add_job to run every 5 minutes indefinitely?
What are the exact values of #freq_type=4,#freq_interval=64, freq_subday_type=0x4,#freq_subday_interval=10, #freq_relative_interval=0 that I should be using ?
Try this.... #user2748147
Declare #job nvarchar(128),
#mycommand nvarchar(max),
#servername nvarchar(28),
#databasename nvarchar(50),
#startdate nvarchar(8),
#starttime nvarchar(8)
SET #job = 'myJob'
SET #mycommand = 'Select * from myTable'
SET #startdate = '20151219' -- The date December 19, 2015
SET #starttime = '160000' -- The time, 16:00:00
SET #servername = 'myservername'
SET #databasename = 'yourdatabasename'
--Add a job
EXEC dbo.sp_add_job
#job_name = #job ;
--Add a job step named process step. This step runs the stored procedure
EXEC sp_add_jobstep
#job_name = #job,
#step_name = N'process step',
#subsystem = N'TSQL',
#database_name = #databasename,
#command = #mycommand
--Schedule the job at a specified date and time
exec sp_add_jobschedule #job_name = #job,
#name = 'MySchedule',
#freq_type=4,
#freq_interval=4,
#freq_subday_type=0x4,
#freq_subday_interval = 5,
#active_start_date = #startdate,
#active_start_time = #starttime
-- Add the job to the SQL Server Server
EXEC dbo.sp_add_jobserver
#job_name = #job,
#server_name = #servername

Incorrect syntax near 'set Dynamic sql query

/* When I execute this procedure in sql server it execute correctly but when I execute through coding i get this error "Incorrect syntax near set"
Thanks in advance*/
ALTER PROCEDURE [dbo].[updateCitationTrust]
#tblName varchar(50),
#updatedTableName varchar(50)
AS
DECLARE #sql NVARCHAR(4000)
Declare #ParamDefinition AS NVarchar(2000)
BEGIN
--BEGIN TRANSACTION
set #sql='Update '+#updatedTableName+ ' set [Citation Flow]=m2.[Citation Flow],'+
' [Trust Flow]=m2.[Trust Flow]'+
' FROM '+ #updatedTableName+ ' m1 '+
' INNER JOIN '+ #tblName+' m2'+
' on m1.[Linking Domain]=m2.[Item]'
Set #ParamDefinition = '#tblName varchar(50),
#updatedTableName varchar(50)'
Execute sp_Executesql #sql,
#ParamDefinition,
#tblName,
#updatedTableName
If ##ERROR <> 0 GoTo ErrorHandler
Set NoCount OFF
Return(0)
ErrorHandler:
Return(##ERROR)
END
If the object names passed as parameter values that don't confirm to the rules for regular identifiers (https://msdn.microsoft.com/en-us/library/ms175874.aspx?f=255&MSPPError=-2147217396), need to be quoted. USe the QUOTENAME function. This will also mitigate the risk of SQL injection.
ALTER PROCEDURE [dbo].[updateCitationTrust]
#tblName varchar(50),
#updatedTableName varchar(50)
AS
DECLARE #sql NVARCHAR(4000)
Declare #ParamDefinition AS NVarchar(2000)
BEGIN
--BEGIN TRANSACTION
set #sql='Update '+QUOTENAME(#updatedTableName)+ ' set [Citation Flow]=m2.[Citation Flow],'+
' [Trust Flow]=m2.[Trust Flow]'+
' FROM '+ QUOTENAME(#updatedTableName)+ ' m1 '+
' INNER JOIN '+ QUOTENAME(#tblName)+' m2'+
' on m1.[Linking Domain]=m2.[Item]'
Set #ParamDefinition = '#tblName varchar(50),
#updatedTableName varchar(50)'
Execute sp_Executesql #sql,
#ParamDefinition,
#tblName,
#updatedTableName
If ##ERROR <> 0 GoTo ErrorHandler
Set NoCount OFF
Return(0)
ErrorHandler:
Return(##ERROR)
END

Resources