Combining Stored Procedures Result Sets [duplicate] - sql

This question already has answers here:
UNION the results of multiple stored procedures
(5 answers)
Closed 4 years ago.
I am executing multiple stored procedures which return results, but I want it to look like one result set. I tried UNION ALL but that only works with SELECT statements.
EXEC TaskSummary #TaskName = "Demo", #Days ="5", #GroupName = "Charlie"
EXEC TaskSummary #TaskName = "Framing", #Days="15", #GroupName = "Charlie"
EXEC TaskSummary #TaskName = "Electrical Rough-In", #Days= 7, #GroupName = "Foxtrot"
EXEC TaskSummary #TaskName = "Insulation", #Days = 2, #GroupName = "Charlie"
EXEC TaskSummary #TaskName = "Exterior Doors", #Days= 2, #GroupName = "Charlie"
EXEC TaskSummary #TaskName = "Install Windows", #Days= 2, #GroupName= "Charlie"
EXEC TaskSummary #TaskName = "Bathroom Tiles", #Days= 6, #GroupName = "Charlie"
EXEC TaskSummary #TaskName = "Prime Walls" , #Days= "2", #GroupName = "Bravo"
EXEC TaskSummary #TaskName = "Painting Interior" , #Days= "3" , #GroupName = "Charlie"
EXEC TaskSummary #TaskName = "Mill Work", #Days="3", #GroupName= "Charlie"
EXEC TaskSummary #TaskName = "Backsplash Install" , #Days= "1" , #GroupName= "Charlie"
EXEC TaskSummary #TaskName = "Electrical Dress-Up" , #Days="1" , #GroupName= "Foxtrot"
EXEC TaskSummary #TaskName = "Interior Hardware Install", #Days= "2" , #GroupName= "Charlie"
EXEC TaskSummary #TaskName = "Final Touch Up", #Days= "2", #GroupName = "Bravo"
EXEC TaskSummary #TaskName = "Punch List", #Days= "2", #GroupName= "Charlie"

You can create one temp table and insert all stored procedure result within it, then perform a select query:
--CREATE TEMP TABLE
CREATE TABLE #TBL(Column1 ....)
--Eexute all stored procedures with an insert statment
INSERT INTO #TBL
EXEC TaskSummary #TaskName = "Demo", #Days ="5", #GroupName = "Charlie"
INSERT INTO #TBL
EXEC TaskSummary #TaskName = "Framing", #Days="15", #GroupName = "Charlie"
...
--Select data from temp table
SELECT * FROM #TBL

You can use a table variable to collect all the results.
DECLARE #u TABLE
(<columns as the result of TaskSummary regarding number, order and type>);
INSERT INTO #u
EXECUTE TaskSummary <parameters>;
...
INSERT INTO #u
EXECUTE TaskSummary <other parameters>;
SELECT *
FROM #u;

Related

Append dynamic query json

I am writing a dynamic update statement in sql and I want to append json node in existing json by using json query.
DECLARE #Query NVARCHAR(MAX);
DECLARE #TS VARCHAR(50) = 'TS20160101'
SET #Query =
'UPDATE testtable
SET metricdata = Json_modify(metricdata, ''$. ' + #TS + '.trend.Value'',
Cast(Json_value(metricdata,
''$.'+ #TS +'.trend.Value'') AS
FLOAT)
+ 5),
AuditTrail = Json_modify(AuditTrail, ''append $.'+ #TS +'.trend'',
Json_query(N''{"value": '+ 'CAST(CAST((CAST(Json_value(metricdata,''$.'+ #TS +'.trend.Value'') AS float) *5) AS float) AS nvarchar(28)) '
+', "ModifiedBy":"Bilal.Asghar#visionet.com", "ModifiedDate": "2022-01-13 10:10:23.447"}''))
WHERE id IN ( 1, 2, 3 ) '
EXEC (#Query)
I have 3 rows in table with Id 1,2,3.
Metric Data rows:
{"mape":{"Value":"0","ModifiedBy":"System","ModifiedDate":"2022-01-14 13:55:09.317"},"TS20160101":{"trend":{"Value":9.165000000000000e+003,"ModifiedBy":"System","ModifiedDate":"2022-01-14 13:55:09.317"}}}
{"mape":{"Value":"0","ModifiedBy":"System","ModifiedDate":"2022-01-14 13:55:09.317"},"TS20160101":{"trend":{"Value":9.265000000000000e+003,"ModifiedBy":"System","ModifiedDate":"2022-01-14 13:55:09.317"}}}
{"mape":{"Value":"0","ModifiedBy":"System","ModifiedDate":"2022-01-14 13:55:09.317"},"TS20160101":{"trend":{"Value":9.365000000000000e+003,"ModifiedBy":"System","ModifiedDate":"2022-01-14 13:55:09.317"}}}
Audit Trail rows
{"TS20160101":{"trend":[{"value":79987,"ModifiedBy":"Systems","ModifiedDate":"2021-09-24 19:21:10.443"},{"value": 100, "ModifiedBy":"Bilal.Asghar#visionet.com", "ModifiedDate": "2022-01-13 10:10:23.447"},{"value": 9.155000000000000e+003, "ModifiedBy":"Bilal.Asghar#visionet.com", "ModifiedDate": "2022-01-13 10:10:23.447"},{"value": 45800, "ModifiedBy":"Bilal.Asghar#visionet.com", "ModifiedDate": "2022-01-13 10:10:23.447"}]}}
{"TS20160101":{"trend":[{"value":79987,"ModifiedBy":"Systems","ModifiedDate":"2021-09-24 19:21:10.443"},{"value": 100, "ModifiedBy":"Bilal.Asghar#visionet.com", "ModifiedDate": "2022-01-13 10:10:23.447"},{"value": 9.255000000000000e+003, "ModifiedBy":"Bilal.Asghar#visionet.com", "ModifiedDate": "2022-01-13 10:10:23.447"},{"value": 46300, "ModifiedBy":"Bilal.Asghar#visionet.com", "ModifiedDate": "2022-01-13 10:10:23.447"}]}}
{"TS20160101":{"trend":[{"value":79987,"ModifiedBy":"Systems","ModifiedDate":"2021-09-24 19:21:10.443"},{"value": 100, "ModifiedBy":"Bilal.Asghar#visionet.com", "ModifiedDate": "2022-01-13 10:10:23.447"},{"value": 9.355000000000000e+003, "ModifiedBy":"Bilal.Asghar#visionet.com", "ModifiedDate": "2022-01-13 10:10:23.447"},{"value": 46800, "ModifiedBy":"Bilal.Asghar#visionet.com", "ModifiedDate": "2022-01-13 10:10:23.447"}]}}
I want to modify metric data json and add node in audit trail.
My issue is this in audit trail column its appending node as a string and not calculating value
Answer: I don't tnink that you need a dynamic statement here. As is explained in the documentation: ... in SQL Server 2017 (14.x) and in Azure SQL Database, you can provide a variable as the value of path.... The following statement, based on the attempt from the question is a possible solution:
DECLARE #ts nvarchar(max) = N'TS20160101'
UPDATE testtable
SET metricdata = JSON_MODIFY (
metricdata,
'$.' + #ts + '.trend.value',
TRY_CONVERT(int, JSON_VALUE(MetricData, '$.' + #ts + '.trend.value') * 7)
),
AuditTrail = JSON_MODIFY (
AuditTrail,
'append $.' + #ts + '.trend',
(
SELECT
TRY_CONVERT(int, JSON_VALUE(MetricData, '$.' + #ts + '.trend.value') * 7) AS [Value],
'2022-01-13 10:10:23.447' AS [ModifiedDate],
'Bilal.Asghar#*.com' AS ModifiedBy
FOR JSON PATH
)
)
Update: If the table name is dynamic, you need a dynamic statement:
DECLARE #path1 nvarchar(max) = N'$.TS20160101.trend.value'
DECLARE #path2 nvarchar(max) = N'append $.TS20160101.trend'
DECLARE #table sysname = N'testtable'
DECLARE #stmt nvarchar(max)
DECLARE #prms nvarchar(max)
SET #stmt = CONCAT(
N' UPDATE ', QUOTENAME(#table),
N' SET ',
N'MetricData = JSON_MODIFY (',
N'MetricData, ',
N'#path1, ',
N'TRY_CONVERT(int, JSON_VALUE(MetricData, #path1) * 7)',
N'), ',
N'AuditTrail = JSON_MODIFY (',
N'AuditTrail, ',
N'#path2, ',
N'(',
N'SELECT ',
N'TRY_CONVERT(int, JSON_VALUE(MetricData, #path1) * 7) AS [Value], ',
N'''2022-01-13 10:10:23.447'' AS [ModifiedDate], ',
N'''Bilal.Asghar#*.com'' AS ModifiedBy ',
N'FOR JSON PATH ',
N') ',
N') '
)
SET #prms = N'#path1 nvarchar(max), #path2 nvarchar(max)'
EXEC sp_executesql #stmt, #prms, #path1, #path2

SQL Server Naming Policy Management blocking correctly named stored procedure

I want to enforce a naming convention for user stored procedures to begin with 'usp_'. I created a policy and I receive an error no matter what the name of the stored procedure.
The condition is as follows:
DECLARE #condition_id INT
EXEC msdb.dbo.sp_syspolicy_add_condition
#name = N'con_multipart_name_usp_prefix',
#description = N'',
#facet = N'IMultipartNameFacet',
#expression = N'<Operator>
<TypeClass>Bool</TypeClass>
<OpType>LIKE</OpType>
<Count>2</Count>
<Attribute>
<TypeClass>String</TypeClass>
<Name>Name</Name>
</Attribute>
<Constant>
<TypeClass>String</TypeClass>
<ObjType>System.String</ObjType>
<Value>usp_%</Value>
</Constant>
</Operator>',
#is_name_condition = 2,
#obj_name = N'usp_%',
#condition_id = #condition_id OUTPUT
SELECT #condition_id
GO
Here is the SSMS properties box for the condition
The policy is as follows:
Declare #object_set_id int
EXEC msdb.dbo.sp_syspolicy_add_object_set #object_set_name=N'policy_naming_usp_prefix_ObjectSet', #facet=N'IMultipartNameFacet', #object_set_id=#object_set_id OUTPUT
Select #object_set_id
Declare #target_set_id int
EXEC msdb.dbo.sp_syspolicy_add_target_set #object_set_name=N'policy_naming_usp_prefix_ObjectSet', #type_skeleton=N'Server/Database/Sequence', #type=N'SEQUENCE', #enabled=False, #target_set_id=#target_set_id OUTPUT
Select #target_set_id
EXEC msdb.dbo.sp_syspolicy_add_target_set_level #target_set_id=#target_set_id, #type_skeleton=N'Server/Database/Sequence', #level_name=N'Sequence', #condition_name=N'', #target_set_level_id=0
EXEC msdb.dbo.sp_syspolicy_add_target_set_level #target_set_id=#target_set_id, #type_skeleton=N'Server/Database', #level_name=N'Database', #condition_name=N'', #target_set_level_id=0
EXEC msdb.dbo.sp_syspolicy_add_target_set #object_set_name=N'policy_naming_usp_prefix_ObjectSet', #type_skeleton=N'Server/Database/StoredProcedure', #type=N'PROCEDURE', #enabled=True, #target_set_id=#target_set_id OUTPUT
Select #target_set_id
EXEC msdb.dbo.sp_syspolicy_add_target_set_level #target_set_id=#target_set_id, #type_skeleton=N'Server/Database/StoredProcedure', #level_name=N'StoredProcedure', #condition_name=N'', #target_set_level_id=0
EXEC msdb.dbo.sp_syspolicy_add_target_set_level #target_set_id=#target_set_id, #type_skeleton=N'Server/Database', #level_name=N'Database', #condition_name=N'', #target_set_level_id=0
EXEC msdb.dbo.sp_syspolicy_add_target_set #object_set_name=N'policy_naming_usp_prefix_ObjectSet', #type_skeleton=N'Server/Database/Synonym', #type=N'SYNONYM', #enabled=False, #target_set_id=#target_set_id OUTPUT
Select #target_set_id
EXEC msdb.dbo.sp_syspolicy_add_target_set_level #target_set_id=#target_set_id, #type_skeleton=N'Server/Database/Synonym', #level_name=N'Synonym', #condition_name=N'', #target_set_level_id=0
EXEC msdb.dbo.sp_syspolicy_add_target_set_level #target_set_id=#target_set_id, #type_skeleton=N'Server/Database', #level_name=N'Database', #condition_name=N'', #target_set_level_id=0
EXEC msdb.dbo.sp_syspolicy_add_target_set #object_set_name=N'policy_naming_usp_prefix_ObjectSet', #type_skeleton=N'Server/Database/Table', #type=N'TABLE', #enabled=False, #target_set_id=#target_set_id OUTPUT
Select #target_set_id
EXEC msdb.dbo.sp_syspolicy_add_target_set_level #target_set_id=#target_set_id, #type_skeleton=N'Server/Database/Table', #level_name=N'Table', #condition_name=N'', #target_set_level_id=0
EXEC msdb.dbo.sp_syspolicy_add_target_set_level #target_set_id=#target_set_id, #type_skeleton=N'Server/Database', #level_name=N'Database', #condition_name=N'', #target_set_level_id=0
EXEC msdb.dbo.sp_syspolicy_add_target_set #object_set_name=N'policy_naming_usp_prefix_ObjectSet', #type_skeleton=N'Server/Database/UserDefinedFunction', #type=N'FUNCTION', #enabled=False, #target_set_id=#target_set_id OUTPUT
Select #target_set_id
EXEC msdb.dbo.sp_syspolicy_add_target_set_level #target_set_id=#target_set_id, #type_skeleton=N'Server/Database/UserDefinedFunction', #level_name=N'UserDefinedFunction', #condition_name=N'', #target_set_level_id=0
EXEC msdb.dbo.sp_syspolicy_add_target_set_level #target_set_id=#target_set_id, #type_skeleton=N'Server/Database', #level_name=N'Database', #condition_name=N'', #target_set_level_id=0
EXEC msdb.dbo.sp_syspolicy_add_target_set #object_set_name=N'policy_naming_usp_prefix_ObjectSet', #type_skeleton=N'Server/Database/UserDefinedType', #type=N'TYPE', #enabled=False, #target_set_id=#target_set_id OUTPUT
Select #target_set_id
EXEC msdb.dbo.sp_syspolicy_add_target_set_level #target_set_id=#target_set_id, #type_skeleton=N'Server/Database/UserDefinedType', #level_name=N'UserDefinedType', #condition_name=N'', #target_set_level_id=0
EXEC msdb.dbo.sp_syspolicy_add_target_set_level #target_set_id=#target_set_id, #type_skeleton=N'Server/Database', #level_name=N'Database', #condition_name=N'', #target_set_level_id=0
EXEC msdb.dbo.sp_syspolicy_add_target_set #object_set_name=N'policy_naming_usp_prefix_ObjectSet', #type_skeleton=N'Server/Database/View', #type=N'VIEW', #enabled=False, #target_set_id=#target_set_id OUTPUT
Select #target_set_id
EXEC msdb.dbo.sp_syspolicy_add_target_set_level #target_set_id=#target_set_id, #type_skeleton=N'Server/Database/View', #level_name=N'View', #condition_name=N'', #target_set_level_id=0
EXEC msdb.dbo.sp_syspolicy_add_target_set_level #target_set_id=#target_set_id, #type_skeleton=N'Server/Database', #level_name=N'Database', #condition_name=N'', #target_set_level_id=0
EXEC msdb.dbo.sp_syspolicy_add_target_set #object_set_name=N'policy_naming_usp_prefix_ObjectSet', #type_skeleton=N'Server/Database/XmlSchemaCollection', #type=N'XMLSCHEMACOLLECTION', #enabled=False, #target_set_id=#target_set_id OUTPUT
Select #target_set_id
EXEC msdb.dbo.sp_syspolicy_add_target_set_level #target_set_id=#target_set_id, #type_skeleton=N'Server/Database/XmlSchemaCollection', #level_name=N'XmlSchemaCollection', #condition_name=N'', #target_set_level_id=0
EXEC msdb.dbo.sp_syspolicy_add_target_set_level #target_set_id=#target_set_id, #type_skeleton=N'Server/Database', #level_name=N'Database', #condition_name=N'', #target_set_level_id=0
GO
Declare #policy_id int
EXEC msdb.dbo.sp_syspolicy_add_policy #name=N'policy_naming_usp_prefix', #condition_name=N'con_multipart_name_usp_prefix', #policy_category=N'', #description=N'', #help_text=N'', #help_link=N'', #schedule_uid=N'00000000-0000-0000-0000-000000000000', #execution_mode=1, #is_enabled=True, #policy_id=#policy_id OUTPUT, #root_condition_name=N'', #object_set=N'policy_naming_usp_prefix_ObjectSet'
Select #policy_id
GO
Here is the SSMS properties box for the policy
When I create a sample stored procedure that conforms to this naming convention, the policy blocks the create statement.
Here is the sample stored procedure:
CREATE PROCEDURE usp_test
AS
print 'test'
Finally, here is the error output:
Policy 'policy_naming_usp_prefix' has been violated by 'SQLSERVER:\SQL\SERVERNAME\Databases\DBNAME\StoredProcedures\dbo.usp_test'.
This transaction will be rolled back.
Policy condition: '#Name LIKE 'usp_%''
Policy description: ''
Additional help: '' : ''
Statement: '
CREATE PROCEDURE usp_test
AS
print 'test''.
Msg 515, Level 16, State 2, Procedure msdb.sys.sp_syspolicy_execute_policy, Line 69 [Batch Start Line 0]
Cannot insert the value NULL into column 'target_query_expression', table 'msdb.dbo.syspolicy_policy_execution_history_details_internal'; column does not allow nulls. INSERT fails.
The statement has been terminated.
What am I doing wrong here?
Based on your comments of being on the RTM version of 2017, you will need to updated to CU2 (at a minimum) as described in this KB.
Here's a link to that cumulative update.
However, if you are using Query Store you need CU3 instead.
Lastly, you could just come "up to date" and get CU13.

Send email does not printing query result in csv

I'm using following code to send an attachment in email in CSV format, this is working fine but when i try to use the original query i-e select col1, col2, col3 .. from DBTable in place of test query select ''1'', ''2'', ''3'', ''4'' email is not being sent, even there is not any error but email not being sent, stored procedure get executed in the same way with both queries.
EXEC msdb..sp_send_dbmail #profile_name='Notificatins and Alerts',
#recipients = #EmailRecipient,
#subject = #MessageSubject,
#body = #MessageBody,
#body_format = 'HTML',
#query='SET NOCOUNT ON;
select ''sep=,''
select ''1'', ''2'', ''3'', ''4'' ',
--select ''1'', ''2'', ''3'', ''4''
#attach_query_result_as_file=1,
#query_attachment_filename = 'Results.csv',
#query_result_separator =',',
#query_result_no_padding=1, --trim
--#query_result_width=32767, --stop wordwrap
#exclude_query_output =1,
#append_query_error = 0,
#query_result_header =0;
can any one help me on that.
Here is the solution. Hope this will help someone:
EXEC msdb..sp_send_dbmail #profile_name='Notificatins and Alerts',
#recipients = #EmailRecipient,
#subject = #MessageSubject,
#body = #MessageBody,
#body_format = 'HTML',
#query='SET NOCOUNT ON;
select ''sep=,''
select col1, col2, col3 .. from dbName.dbo.DBTable ',
--select ''1'', ''2'', ''3'', ''4''
#attach_query_result_as_file=1,
#query_attachment_filename = 'Results.csv',
#query_result_separator =',',
#query_result_no_padding=1, --trim
--#query_result_width=32767, --stop wordwrap
#exclude_query_output =1,
#append_query_error = 0,
#query_result_header =0;
simply one have to use DBName.dbo with table name that was missing in my query.

Subquery returned more than 1 value. This is not permitted when the subquery follows =,.. or when the subquery is used as an expression

I have this following stored procedure to make a reservation .I have not done the front end to insert the values so I use the execute stored procedure from the sql server menu to insert into the database but it gives me the subquery returned more than 1 value and 1 row affected message
ALTER PROCEDURE [dbo].[Usp_makereservation]
--roombookingdetails
#refno VARCHAR(50),
#propertyid int,
#roomtype VARCHAR(3),
#groupcode VARCHAR(30),
#companycode VARCHAR(10),
#arrivaldate DATETIME,
#arrivalplan VARCHAR(3),
#departuredate DATETIME,
#departureplan VARCHAR(3),
#createdby INT,
--roombookingguestdetails
#subsrno VARCHAR(50),
#roomno VARCHAR(30),
#guesttitle VARCHAR(30),
#lname VARCHAR(50),
#fname VARCHAR(50),
#mname VARCHAR(50),
#address VARCHAR(100),
#city VARCHAR(30),
#state VARCHAR(30),
#country INT,
#zipcode VARCHAR(50),
#telno VARCHAR(15),
#mobile VARCHAR(15),
#fax VARCHAR(50),
#gueststatus INT,
#designation VARCHAR(50),
#occupation VARCHAR(50),
#arrivalfrom VARCHAR(50),
#departureto VARCHAR(50),
#leader BIT,
#spclinstrctn VARCHAR(1000),
#checkinflg BIT,
--roombookingoccupancy
#singlebooked INT,
#singleprovisional INT,
#singleconfirmed INT,
#singlewaitlisted INT,
#doublebooked INT,
#doubleprovisional INT,
#doubleconfirmed INT,
#doublewaitlisted INT,
#triplebooked INT,
#tripleprovisional INT,
#tripleconfirmed INT,
#triplewaitlisted INT,
#quadbooked INT,
#quadprovisional INT,
#quadconfirmed INT,
#quadwaitlisted INT,
#marketsegID INT,
#businesssrcID INT,
#guestcategoryID INT,
#gueststatusID INT,
#totalpax INT,
#adultpax INT,
#childpax INT,
#infantpax INT,
#extraadultpax INT,
#extrachildpax INT,
#complementarypax INT,
#noshow INT,
#checkinrooms INT,
#checkinpax INT
AS
BEGIN
BEGIN try
BEGIN TRAN
INSERT INTO roombookingdetails
(reservationno,
srno,
refno,
propertyid,
roomtype,
groupcode,
companycode,
arrivaldate,
arrivalplan,
depaturedate,
depatureplan,
createdon,
createdby)
VALUES ((SELECT Isnull(Max(reservationno) + 1, 1)
FROM roombookingdetails),
(SELECT Isnull(Max(srno) + 1, 1)
FROM roombookingdetails),
#refno,
#propertyid,
#roomtype,
#groupcode,
#companycode,
#arrivaldate,
#arrivalplan,
#departuredate,
#departureplan,
Getdate(),
#createdby)
INSERT INTO roombookingguestdetails
(reservationno,
srno,
subsrno,
roomno,
guesttitle,
lastname,
firstname,
midname,
[address],
city,
[state],
country,
zipcode,
telno,
mobile,
fax,
gueststatus,
designation,
occupation,
arrivalfrom,
depatureto,
leader,
specialinstruction,
checkinflag,
createdon,
createdby)
VALUES ((SELECT [reservationno]
FROM roombookingdetails),
(SELECT Isnull(Max(srno) + 1, 1)
FROM roombookingguestdetails),
#subsrno,
#roomno,
#guesttitle,
#lname,
#fname,
#mname,
#address,
#city,
#state,
#country,
#zipcode,
#telno,
#mobile,
#fax,
#gueststatus,
#designation,
#occupation,
#arrivalfrom,
#departureto,
#leader,
#spclinstrctn,
#checkinflg,
Getdate(),
#createdby)
INSERT INTO roombookingoccupancy
(reservationno,
srno,
singlebooked,
singleprovisional,
singleconfirmed,
singlewaitlisted,
doublebooked,
doubleprovisional,
doubleconfirmed,
doublewaitlisted,
tripplebooked,
trippleprovisional,
trippleconfirmed,
tripplewaitlisted,
quadbooked,
quadprovisional,
quadconfirmed,
quadwaitlisted,
marketsegmentid,
businesssourceid,
guestcategoryid,
gueststatusid,
totalpax,
adultpax,
childpax,
infantpax,
extraadultpax,
extrachildpax,
complementrypax,
noshow,
checkinrooms,
checkinpax,
createdon,
createdby)
VALUES ((SELECT [reservationno]
FROM roombookingdetails),
(SELECT Isnull(Max(srno) + 1, 1)
FROM roombookingoccupancy),
#singlebooked,
#singleprovisional,
#singleconfirmed,
#singlewaitlisted,
#doublebooked,
#doubleprovisional,
#doubleconfirmed,
#doublewaitlisted,
#triplebooked,
#tripleprovisional,
#tripleconfirmed,
#triplewaitlisted,
#quadbooked,
#quadprovisional,
#quadconfirmed,
#quadwaitlisted,
#marketsegID,
#businesssrcID,
#guestcategoryID,
#gueststatusID,
#totalpax,
#adultpax,
#childpax,
#infantpax,
#extraadultpax,
#extrachildpax,
#complementarypax,
#noshow,
#checkinrooms,
#checkinpax,
Getdate(),
#createdby)
COMMIT TRAN
END try
BEGIN catch
PRINT 'Rollback'
SELECT 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
END catch
END
Here is the query generated after selecting execute stored procedure command
DECLARE #return_value int
EXEC #return_value = [dbo].[Usp_makereservation]
#refno = N'12',
#propertyid = 2,
#roomtype = N'R345',
#groupcode = N'G25',
#companycode = N'C422',
#arrivaldate = N'1/2/3',
#arrivalplan = N'fd',
#departuredate = N'5/2/3',
#departureplan = N'gdfgd',
#createdby = 1,
#subsrno = N'g',
#roomno = N'fgd',
#guesttitle = N'fdf',
#lname = N'gdf',
#fname = N'f',
#mname = N'd',
#address = N'dfg',
#city = N'fdg',
#state = N'fd',
#country = 3,
#zipcode = N'rt',
#telno = N'etr',
#mobile = N'et',
#fax = N'r',
#gueststatus = 4,
#designation = N'ertre',
#occupation = N'tert',
#arrivalfrom = N'ret',
#departureto = N'ret',
#leader = 1,
#spclinstrctn = N'er',
#checkinflg = 1,
#singlebooked = 2,
#singleprovisional = 2,
#singleconfirmed = 3,
#singlewaitlisted = 2,
#doublebooked = 23,
#doubleprovisional = 2,
#doubleconfirmed = 3,
#doublewaitlisted = 23,
#triplebooked = 23,
#tripleprovisional = 23,
#tripleconfirmed = 23,
#triplewaitlisted = 23,
#quadbooked = 2,
#quadprovisional = 3,
#quadconfirmed = 24,
#quadwaitlisted = 23,
#marketsegID = 432,
#businesssrcID = 4,
#guestcategoryID = 234,
#gueststatusID = 234,
#totalpax = 234,
#adultpax = 23,
#childpax = 4,
#infantpax = 234,
#extraadultpax = 23,
#extrachildpax = 4234,
#complementarypax = 23,
#noshow = 4,
#checkinrooms = 234,
#checkinpax = 43232
SELECT 'Return Value' = #return_value
GO
There is chanch that your following statement may returns more than single value.
Please check it.
> SELECT [reservationno] FROM roombookingdetails
You have used it in your insert statement.
You have to usewhere clause,Top operator,Min,Max,Avg in your subquery when there is such type of problem or more then 1 record exist.
Replacing this (SELECT [reservationno] FROM roombookingdetails) from first insert
with this
(SELECT Isnull(Max(reservationno) + 1, 1) FROM roombookingguestdetails)
and this (SELECT [reservationno] FROM roombookingdetails) from second insert
with this (SELECT Isnull(Max(reservationno) + 1, 1) FROM (RoomBookingOccupancy)
solved my problem

SQL stored procedure: how to concatenate parameter value?

This is original code:
EXEC #ReturnCode = msdb.dbo.sp_add_jobstep #job_id=#jobId, #step_name=N'TestStep',
#step_id=1,
#cmdexec_success_code=0,
#on_success_action=1,
#on_success_step_id=0,
#on_fail_action=2,
#on_fail_step_id=0,
#retry_attempts=0,
#retry_interval=0,
#os_run_priority=0, #subsystem=N'SSIS',
#command=N'/ISSERVER "\"\SSISDB\FolderName\ProjectName\PackageName.dtsx\"" /SERVER localhost /ENVREFERENCE 9 /Par "\"$ServerOption::LOGGING_LEVEL(Int16)\"";1 /Par "\"$ServerOption::SYNCHRONIZED(Boolean)\"";True /CALLERINFO SQLAGENT /REPORTING E',
#database_name=N'master', ...
I want to do something like this (replace value after ENVREFERENCE in long string with dynamic value):
DECLARE #myVariable int
SET #myVariable = 10
EXEC #ReturnCode = msdb.dbo.sp_add_jobstep #job_id=#jobId, #step_name=N'TestStep',
#step_id=1,
#cmdexec_success_code=0,
#on_success_action=1,
#on_success_step_id=0,
#on_fail_action=2,
#on_fail_step_id=0,
#retry_attempts=0,
#retry_interval=0,
#os_run_priority=0, #subsystem=N'SSIS',
#command=N'/ISSERVER "\"\SSISDB\AccuCenter\AccuCenterDBImport\VehicleMake.dtsx\"" /SERVER localhost /ENVREFERENCE ' + #myVariable + N' /Par "\"$ServerOption::LOGGING_LEVEL(Int16)\"";1 /Par "\"$ServerOption::SYNCHRONIZED(Boolean)\"";True /CALLERINFO SQLAGENT /REPORTING E',
#database_name=N'master'
Couldn't you put the whole in a variable ?
DECLARE #myCommand nvarchar(max)
SET #myCommand = N'/ISSERVER "\"\SSISDB\AccuCenter\AccuCenterDBImport\VehicleMake.dtsx\"" /SERVER localhost /ENVREFERENCE '
+ LTRIM(STR(#myVariable))
+ N' /Par "\"$ServerOption::LOGGING_LEVEL(Int16)\"";1 /Par "\"$ServerOption::SYNCHRONIZED(Boolean)\"";True /CALLERINFO SQLAGENT /REPORTING E'
By the way, you could build it entirely to fit your needs.
Then use it when calling sp_add_jobstep:
EXEC #ReturnCode = msdb.dbo.sp_add_jobstep
#job_id=#jobId,
#step_name=N'TestStep',
#step_id=1,
#cmdexec_success_code=0,
#on_success_action=1,
#on_success_step_id=0,
#on_fail_action=2,
#on_fail_step_id=0,
#retry_attempts=0,
#retry_interval=0,
#os_run_priority=0, #subsystem=N'SSIS',
#command=#myCommand
#database_name=N'master'