Send email does not printing query result in csv - sql

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.

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 - Find frequency of occurance (by row, not word) of most common words in a column

This question has been asked more than a few times, but I can't find the specific answer I need. I have a query that finds the most commonly appearing words in a column in SQL Server and lists them with the count of their appearances. The problem is that if a word appears multiple times in a row, it counts once for each appearance. I would like to only count each word once per row.
So a row with a value of "To be or not to be" would count 'to' and 'be' once each, not twice each for purposes of overall frequency.
Here is the current query, which also strips out common words such as pronouns and replaces all of the commonly occurring separators with spaces. It's a bit old so I suspect it could be a lot neater.
SELECT sep.Col Phrase, count(*) as Qty
FROM (
Select * FROM (
Select value = Upper(RTrim(LTrim(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Title, ',', ' '), '.', ' '), '!', ' '), '+', ' '), ':', ' '), '-', ' '), ';', ' '), '(', ' '), ')', ' '), '/', ' '), '&', ''), '?', ' '), ' ', ' '), ' ', ' '))))
FROM Table
) easyValues
Where value <> ''
) actualValues
Cross Apply dbo.SeparateValues(value, ' ') sep
WHERE sep.Col not in ('', 'THE', 'A', 'AN', 'WHO', 'BOOK', 'AND', 'FOR', 'ON', 'HAVE', 'YOUR', 'HOW', 'WE', 'IN', 'I', 'IT', 'BY', 'SO', 'THEIR', 'IS', 'OR', 'HE', 'OF', 'WHAT'
, 'HIM', 'HIS', 'SHE', 'HER', 'MY', 'FROM', 'US', 'OUR', 'AT', 'ALL', 'BE', 'OF', 'TO', 'YOU', 'WITH', 'THAT', 'THIS', 'WAS', 'ARE', 'THERE', 'BUT', 'HAS'
, '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', 'WILL', 'MORE', 'DIV', 'THAN', 'EACH', 'GET', 'ANY')
and LEN(sep.Col) > 2
GROUP By sep.Col
HAVING count(*) > 1
Appreciate any thoughts on a better way to do this while fixing the issue of repeat words.
You just need to GROUP BY twice.
First by sep.Col and Table.ID to remove duplicates in a row. Your table has some ID column, right?
Second, just by sep.Col to get the final count.
I have also rewritten your query using CTEs to make it readable. At least, for me it is more readable in this way.
WITH
easyValues
AS
(
Select
ID
,value = Upper(RTrim(LTrim(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Title, ',', ' '), '.', ' '), '!', ' '), '+', ' '), ':', ' '), '-', ' '), ';', ' '), '(', ' '), ')', ' '), '/', ' '), '&', ''), '?', ' '), ' ', ' '), ' ', ' '))))
FROM Table
)
,actualValues
AS
(
SELECT
ID
,Value
FROM easyValues
Where value <> ''
)
,SeparateValues
AS
(
SELECT
ID
,sep.Col
FROM
actualValues
Cross Apply dbo.SeparateValues(value, ' ') AS sep
WHERE
sep.Col not in ('', 'THE', 'A', 'AN', 'WHO', 'BOOK', 'AND', 'FOR', 'ON', 'HAVE', 'YOUR', 'HOW', 'WE', 'IN', 'I', 'IT', 'BY', 'SO', 'THEIR', 'IS', 'OR', 'HE', 'OF', 'WHAT'
, 'HIM', 'HIS', 'SHE', 'HER', 'MY', 'FROM', 'US', 'OUR', 'AT', 'ALL', 'BE', 'OF', 'TO', 'YOU', 'WITH', 'THAT', 'THIS', 'WAS', 'ARE', 'THERE', 'BUT', 'HAS'
, '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', 'WILL', 'MORE', 'DIV', 'THAN', 'EACH', 'GET', 'ANY')
and LEN(sep.Col) > 2
)
,UniqueValues
AS
(
SELECT
ID, Col
FROM
SeparateValues
GROUP BY
ID, Col
)
SELECT
Col AS Phrase
,count(*) as Qty
FROM UniqueValues
GROUP By Col
HAVING count(*) > 1
;
As far as I can tell, the STRING_SPLIT function along with CROSS APPLY can give you what you want. You can split the string based on the space delimiter, select each word distinctly, then count in an outer query. I ommitted the part where you don't select specific words for brevity.
Fiddle<>:
CREATE TABLE phrases(phrase NVARCHAR(MAX));
INSERT INTO phrases(phrase)VALUES(N'To be or not to be'),(N'this is not a phrase'),(N'And why is this not another one');
SELECT
w.value,
COUNT(*)
FROM
phrases AS p
CROSS APPLY (
SELECT DISTINCT
value
FROM
STRING_SPLIT(p.phrase,N' ')
) AS w
GROUP BY
w.value;
To achieve your requirement, you can use a FUNCTION to split a string into list of words by delimiter ' ' space. With the help of this function, you can then use some Dynamic SQL like cursor to get the final count.
First create the FUNCTION as-
Source Of code: stackoverflow
CREATE FUNCTION dbo.splitstring ( #stringToSplit VARCHAR(MAX) )
RETURNS #returnList TABLE ([Word] [nvarchar] (500))
AS
BEGIN
DECLARE #name NVARCHAR(255)
DECLARE #pos INT
WHILE CHARINDEX(' ', #stringToSplit) > 0
BEGIN
SELECT #pos = CHARINDEX(' ', #stringToSplit)
SELECT #name = SUBSTRING(#stringToSplit, 1, #pos-1)
INSERT INTO #returnList
SELECT #name
SELECT #stringToSplit = SUBSTRING(#stringToSplit, #pos+1, LEN(#stringToSplit)-#pos)
END
INSERT INTO #returnList
SELECT #stringToSplit
RETURN
END
Then use this CURSOR script to get your final output-
DECLARE #Value VARCHAR(MAX)
DECLARE #WordList TABLE
(
Word VARCHAR(200)
)
DECLARE db_cursor CURSOR
FOR
SELECT Upper(RTrim(LTrim(Replace(Replace(Replace(Replace(Replace
(Replace(Replace(Replace(Replace(Replace(Replace(Replace
(Replace(Replace(title, ',', ' '), '.', ' '), '!', ' '), '+', ' '), ':', ' '), '-', ' '), ';', ' ')
, '(', ' '), ')', ' '), '/', ' '), '&', ''), '?', ' '), ' ', ' '), ' ', ' ')))) [Value]
FROM table
OPEN db_cursor
FETCH NEXT FROM db_cursor INTO #Value
WHILE ##FETCH_STATUS = 0
BEGIN
INSERT INTO #WordList
SELECT DISTINCT Word FROM [dbo].[splitstring](#Value)
WHERE Word NOT IN ('', 'THE', 'A', 'AN', 'WHO', 'BOOK', 'AND', 'FOR', 'ON', 'HAVE', 'YOUR', 'HOW', 'WE', 'IN', 'I', 'IT', 'BY', 'SO', 'THEIR', 'IS', 'OR', 'HE', 'OF', 'WHAT'
, 'HIM', 'HIS', 'SHE', 'HER', 'MY', 'FROM', 'US', 'OUR', 'AT', 'ALL', 'BE', 'OF', 'TO', 'YOU', 'WITH', 'THAT', 'THIS', 'WAS', 'ARE', 'THERE', 'BUT', 'HAS'
, '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', 'WILL', 'MORE', 'DIV', 'THAN', 'EACH', 'GET', 'ANY')
AND LEN(Word) > 2
FETCH NEXT FROM db_cursor INTO #Value
END
CLOSE db_cursor
DEALLOCATE db_cursor
SELECT Word,COUNT(*)
FROM #WordList
GROUP BY Word

Combining Stored Procedures Result Sets [duplicate]

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;

how do i update column (selmanufacturers_id) from the query

SELECT
'S. J. & G. FAZUL ELLAHIE (PVT) LTD.' AS CompanyName,
'E - 46, S.I.T.E., KARACHI - 75700' AS CompanyAddress,
'admin' login_user, 'crm.sjg.local' selhost,
'admin' sellogin, 'sr_salereport' seltoprint,
'SALES REPORT' selreportTitle, '' selflagType,
'SI' selreportType, '' selfrmDate, '' seltoDate,
'' selfromProductId, '' selac_fromProductId_ac,
'' selbrandId, '' selcustomerId, '' selac_customerId_ac,
'' selgodownId, '' selsmId, '' selsalesmanId, '' selcity,
'' selarea, '' selorders_status, 'S' seldst,
'Invoice' selgroup1, '1' selcurrencyid, 'id' seltype,
'D' seldefUnit, '' selmanufacturers_id, 'Report' selyt0,
CAST(docTypeId as varchar(20)) + CAST(documentId as varchar(20)) groupId1,
[dbo].[ITL_DATE_TO_STRING_FOR_SORTING](refDate) groupTitle1,
'' groupId2, '' selgroup2,'' groupTitle2, *
FROM
[dbo].SR_Sale(null, null, 0, 0, 0, 0, N'', N'', 0, N'SI', 0, 0, 1, N'id', N'D') AS TR
WHERE
docType IN ('SI', 'GYM RECEIPT')
This is a general update statement
FROM dbo.SR_Sale
SET selmanufacturers_id ='xxx'
WHERE (TODO: add where-clause here to specify which row needs to be updated)
Assuming selmanufacturers_id does not exist in [dbo].SR_Sale function but contrary to products_id.
IF (OBJECT_ID('tempdb..#tmp_SR_SALE') IS NOT NULL )
BEGIN
DROP TABLE #tmp_SR_SALE
END
SELECT 'S. J. & G. FAZUL ELLAHIE (PVT) LTD.' AS CompanyName ,
'E - 46, S.I.T.E., KARACHI - 75700' AS CompanyAddress ,
'admin' login_user ,
'crm.sjg.local' selhost ,
'admin' sellogin ,
'sr_salereport' seltoprint ,
'SALES REPORT' selreportTitle ,
'' selflagType ,
'SI' selreportType ,
'' selfrmDate ,
'' seltoDate ,
'' selfromProductId ,
'' selac_fromProductId_ac ,
'' selbrandId ,
'' selcustomerId ,
'' selac_customerId_ac ,
'' selgodownId ,
'' selsmId ,
'' selsalesmanId ,
'' selcity ,
'' selarea ,
'' selorders_status ,
'S' seldst ,
'Invoice' selgroup1 ,
'1' selcurrencyid ,
'id' seltype ,
'D' seldefUnit ,
'' selmanufacturers_id ,
'Report' selyt0 ,
CAST(docTypeId AS VARCHAR(20)) + CAST(documentId AS VARCHAR(20)) groupId1 ,
[dbo].[ITL_DATE_TO_STRING_FOR_SORTING](refDate) groupTitle1 ,
'' groupId2 ,
'' selgroup2 ,
'' groupTitle2 ,
*
INTO #tmp_SR_SALE FROM [dbo].SR_Sale(NULL, NULL, 0, 0, 0, 0, N'', N'', 0, N'SI', 0, 0, 1,
N'id', N'D') AS TR
WHERE docType IN ( 'SI', 'GYM RECEIPT' )
UPDATE #tmp_SR_SALE
SET selmanufacturers_id = 'value here'
WHERE products_id = 9031
SELECT * FROM #tmp_SR_SALE

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