Related
I have this code for my stored procedure:
create or alter procedure udpReservationFilter
#FName nvarchar(160),
#LName nvarchar(160),
#Category nvarchar(160),
#Number int,
#TotalCount int OUT,
#ColumnName nvarchar(100) = 'M.Id',
#SortDesc bit = 0,
#Page int = 1,
#PageSize int = 2
as
begin
declare #sqlWhere nvarchar(max) = ''
declare #whereParams nvarchar(1000) = N' #FName nvarchar(160),
#LName nvarchar(160),
#Category nvarchar(160),
#Number int, #OffsetRows int, #PageSize int'
declare #countParams nvarchar(1000) = N' #FName nvarchar(160),
#LName nvarchar(160),
#Category nvarchar(160),
#Number int,
#TotalCount int OUT'
if len(trim(#FName)) > 0
set #sqlWhere += ' AND c.FName like ''%'' + #FName + ''%'' '
if len(trim(#LName)) > 0
set #sqlWhere += ' AND c.LName like #LName '
if len(trim(#Category))> 0
set #sqlWhere += ' AND r.Category like #Category '
if (#Number > 0)
set #sqlWhere += ' AND r.Number = #Number '
---------------- counting total results -------------------
declare #sqlCount nvarchar(1000) = N' select #TotalCount = count(*) from Reservations M '
if len(#sqlWhere) > 0
set #sqlCount = #sqlCount + ' where ' + (SUBSTRING(#sqlWhere, 5 , 60))
exec sp_executesql #sqlCount,
#countParams,
#FName = #FName,
#LName = #LName,
#Category = #Category,
#Number = #Number,
#TotalCount = #TotalCount OUT
declare #sql nvarchar(max) = N' select M.*, c.*, r.Category, r.Number, r.Price, r.Status
from Reservations M, Client c, Rooms r
where M.ClientId=c.ID and M.RoomId=r.Id'
+ #sqlWhere
+ ' order by ' + #ColumnName
+ ' offset #OffsetRows rows fetch next #PageSize rows only'
--M.*, c.*, r.Number, r.category, r.Price, r.status
declare #Offset int = (#Page-1)*#PageSize
if #Offset < 0
set #Offset = 0
exec sp_executesql #sql,
#whereParams,
#FName = #FName,
#LName =#LName,
#Category = #Category,
#Number = #Number,
#OffsetRows = #Offset,
#PageSize = #PageSize
end
I'm getting this error:
The multi-part identifier "column_name" could not be bound.
when executing the query.
declare #cnt int
exec udpReservationFilter
#FName = null,
#LName = null,
#Category = null,
#Number = null,
#TotalCount = #cnt OUT,
#PageSize = 3
When I provide parameters it is above error and gives the matched result this error stops my asp.net core app and if there is no parameters provided its compiling without error
Here is more detailed error :
Msg 4104, Level 16, State 1, Line 5
The multi-part identifier "c.FName" could not be bound.
(1 row affected)
I tried to use the answer given Here. But Azure SQL does not have 'sp_MSForEachTable'.
Any help would be appreciated
sp_MSForEachTable is a not documented stored procedure.
We can manually create it in Azure SQL database.
Bellow is the whole statement of the full sp_MSForEachTable:
Step 1: create [dbo].[sp_MSforeach_worker]:
CREATE proc [dbo].[sp_MSforeach_worker]
#command1 nvarchar(2000), #replacechar nchar(1) = N'?', #command2 nvarchar(2000) = null, #command3 nvarchar(2000) = null, #worker_type int =1
as
create table #qtemp ( /* Temp command storage */
qnum int NOT NULL,
qchar nvarchar(2000) COLLATE database_default NULL
)
set nocount on
declare #name nvarchar(517), #namelen int, #q1 nvarchar(2000), #q2 nvarchar(2000)
declare #q3 nvarchar(2000), #q4 nvarchar(2000), #q5 nvarchar(2000)
declare #q6 nvarchar(2000), #q7 nvarchar(2000), #q8 nvarchar(2000), #q9 nvarchar(2000), #q10 nvarchar(2000)
declare #cmd nvarchar(2000), #replacecharindex int, #useq tinyint, #usecmd tinyint, #nextcmd nvarchar(2000)
declare #namesave nvarchar(517), #nametmp nvarchar(517), #nametmp2 nvarchar(258)
declare #local_cursor cursor
if #worker_type=1
set #local_cursor = hCForEachDatabase
else
set #local_cursor = hCForEachTable
open #local_cursor
fetch #local_cursor into #name
while (##fetch_status >= 0) begin
select #namesave = #name
select #useq = 1, #usecmd = 1, #cmd = #command1, #namelen = datalength(#name)
while (#cmd is not null) begin /* Generate #q* for exec() */
select #replacecharindex = charindex(#replacechar, #cmd)
while (#replacecharindex <> 0) begin
/* 7.0, if name contains ' character, and the name has been single quoted in command, double all of them in dbname */
/* if the name has not been single quoted in command, do not doulbe them */
/* if name contains ] character, and the name has been [] quoted in command, double all of ] in dbname */
select #name = #namesave
select #namelen = datalength(#name)
declare #tempindex int
if (substring(#cmd, #replacecharindex - 1, 1) = N'''') begin
/* if ? is inside of '', we need to double all the ' in name */
select #name = REPLACE(#name, N'''', N'''''')
end else if (substring(#cmd, #replacecharindex - 1, 1) = N'[') begin
/* if ? is inside of [], we need to double all the ] in name */
select #name = REPLACE(#name, N']', N']]')
end else if ((#name LIKE N'%].%]') and (substring(#name, 1, 1) = N'[')) begin
/* ? is NOT inside of [] nor '', and the name is in [owner].[name] format, handle it */
/* !!! work around, when using LIKE to find string pattern, can't use '[', since LIKE operator is treating '[' as a wide char */
select #tempindex = charindex(N'].[', #name)
select #nametmp = substring(#name, 2, #tempindex-2 )
select #nametmp2 = substring(#name, #tempindex+3, len(#name)-#tempindex-3 )
select #nametmp = REPLACE(#nametmp, N']', N']]')
select #nametmp2 = REPLACE(#nametmp2, N']', N']]')
select #name = N'[' + #nametmp + N'].[' + #nametmp2 + ']'
end else if ((#name LIKE N'%]') and (substring(#name, 1, 1) = N'[')) begin
/* ? is NOT inside of [] nor '', and the name is in [name] format, handle it */
/* j.i.c., since we should not fall into this case */
/* !!! work around, when using LIKE to find string pattern, can't use '[', since LIKE operator is treating '[' as a wide char */
select #nametmp = substring(#name, 2, len(#name)-2 )
select #nametmp = REPLACE(#nametmp, N']', N']]')
select #name = N'[' + #nametmp + N']'
end
/* Get the new length */
select #namelen = datalength(#name)
/* start normal process */
if (datalength(#cmd) + #namelen - 1 > 2000) begin
/* Overflow; put preceding stuff into the temp table */
if (#useq > 9) begin
close #local_cursor
if #worker_type=1
deallocate hCForEachDatabase
else
deallocate hCForEachTable
return 1
end
if (#replacecharindex < #namelen) begin
/* If this happened close to beginning, make sure expansion has enough room. */
/* In this case no trailing space can occur as the row ends with #name. */
select #nextcmd = substring(#cmd, 1, #replacecharindex)
select #cmd = substring(#cmd, #replacecharindex + 1, 2000)
select #nextcmd = stuff(#nextcmd, #replacecharindex, 1, #name)
select #replacecharindex = charindex(#replacechar, #cmd)
insert #qtemp values (#useq, #nextcmd)
select #useq = #useq + 1
continue
end
/* Move the string down and stuff() in-place. */
/* Because varchar columns trim trailing spaces, we may need to prepend one to the following string. */
/* In this case, the char to be replaced is moved over by one. */
insert #qtemp values (#useq, substring(#cmd, 1, #replacecharindex - 1))
if (substring(#cmd, #replacecharindex - 1, 1) = N' ') begin
select #cmd = N' ' + substring(#cmd, #replacecharindex, 2000)
select #replacecharindex = 2
end else begin
select #cmd = substring(#cmd, #replacecharindex, 2000)
select #replacecharindex = 1
end
select #useq = #useq + 1
end
select #cmd = stuff(#cmd, #replacecharindex, 1, #name)
select #replacecharindex = charindex(#replacechar, #cmd)
end
/* Done replacing for current #cmd. Get the next one and see if it's to be appended. */
select #usecmd = #usecmd + 1
select #nextcmd = case (#usecmd) when 2 then #command2 when 3 then #command3 else null end
if (#nextcmd is not null and substring(#nextcmd, 1, 2) = N'++') begin
insert #qtemp values (#useq, #cmd)
select #cmd = substring(#nextcmd, 3, 2000), #useq = #useq + 1
continue
end
/* Now exec() the generated #q*, and see if we had more commands to exec(). Continue even if errors. */
/* Null them first as the no-result-set case won't. */
select #q1 = null, #q2 = null, #q3 = null, #q4 = null, #q5 = null, #q6 = null, #q7 = null, #q8 = null, #q9 = null, #q10 = null
select #q1 = qchar from #qtemp where qnum = 1
select #q2 = qchar from #qtemp where qnum = 2
select #q3 = qchar from #qtemp where qnum = 3
select #q4 = qchar from #qtemp where qnum = 4
select #q5 = qchar from #qtemp where qnum = 5
select #q6 = qchar from #qtemp where qnum = 6
select #q7 = qchar from #qtemp where qnum = 7
select #q8 = qchar from #qtemp where qnum = 8
select #q9 = qchar from #qtemp where qnum = 9
select #q10 = qchar from #qtemp where qnum = 10
truncate table #qtemp
exec (#q1 + #q2 + #q3 + #q4 + #q5 + #q6 + #q7 + #q8 + #q9 + #q10 + #cmd)
select #cmd = #nextcmd, #useq = 1
end
fetch #local_cursor into #name
end /* while FETCH_SUCCESS */
close #local_cursor
if #worker_type=1
deallocate hCForEachDatabase
else
deallocate hCForEachTable
return 0
GO
Step 2: Create proc [dbo].[sp_MSforeachtable]
CREATE proc [dbo].[sp_MSforeachtable]
#command1 nvarchar(2000), #replacechar nchar(1) = N'?', #command2 nvarchar(2000) = null,
#command3 nvarchar(2000) = null, #whereand nvarchar(2000) = null,
#precommand nvarchar(2000) = null, #postcommand nvarchar(2000) = null
AS
declare #mscat nvarchar(12)
select #mscat = ltrim(str(convert(int, 0x0002)))
if (#precommand is not null)
exec(#precommand)
exec(N'declare hCForEachTable cursor global for select ''['' + REPLACE(schema_name(syso.schema_id), N'']'', N'']]'') + '']'' + ''.'' + ''['' + REPLACE(object_name(o.id), N'']'', N'']]'') + '']'' from dbo.sysobjects o join sys.all_objects syso on o.id = syso.object_id '
+ N' where OBJECTPROPERTY(o.id, N''IsUserTable'') = 1 ' + N' and o.category & ' + #mscat + N' = 0 '
+ #whereand)
declare #retval int
select #retval = ##error
if (#retval = 0)
exec #retval = dbo.sp_MSforeach_worker #command1, #replacechar, #command2, #command3, 0
if (#retval = 0 and #postcommand is not null)
exec(#postcommand)
return #retval
GO
Then you won't get the message: "The module 'sp_MSforeachtable' depends on the missing object 'dbo.sp_MSforeach_worker'. The module will still be created; however, it cannot run successfully until the object exists".
Ref: A Copy Of sp_MSforeachtable Stored Procedure For Azure, Uses sp_MSforeach_worker
I tested and it works in Azure SQL database:
Delete all the table data:
--Delete all the table data.
EXEC sp_msforeachtable 'DELETE FROM ?'
Data check:
Hope this helps.
Good afternoon everyone,
Towards the end of my query I start sending PVP Mail Rewards to my players for the game I'm hosting. The issue is that all the queries work successfully until the very last one.
I think this error is generated after the functions I am calling are returning a value causing the script to go bonkers at the end. I can resolve this by splitting all my PVP Mail rewards in to different queries, but I would really prefer keeping them in one master query with all the other things I'm sending.
How would I go about fixing this? Thanks for your time and patience to read this.
Here is the error
> Msg 512, Level 16, State 1, Server LAPTOP-K2EKS8H0, Procedure , Line 0
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
> [21000] [Microsoft][SQL Server Native Client 11.0][SQL Server]Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression. (512)
> Time: 0.029s
-- Create temporary table to hold data from dbo.Characters and dbo.PVPRanking --
USE DNWorld
IF OBJECT_ID('tempdb..#TempAccountTable') IS NOT NULL
begin
drop table #TempAccountTable
end
Select AccountID, G.AccountName, G.CharacterName, PVPLevel, PVPExp, TotalRank
INTO #TempAccountTable
FROM Characters as G
INNER JOIN (
SELECT *, RANK() OVER (ORDER BY TotalRank) AS rn
FROM PvPRanking
Where totalrank between 1 and 100
) as tmp on tmp.CharacterID = G.CharacterID
;
--------------------------------------------------- Rank 1 PvP QC Distribution ---------------------------------------------------
USE DNMembership
GO
DECLARE #AccountName nvarchar(50), #CompensationAmt INT, #i int = 0, #Rank1Rewards int
SET #Rank1Rewards = 1
-- Set and deliver QC by their total rank.
SET #AccountName = (SELECT AccountName FROM #TempAccountTable where TotalRank = 1)
EXEC dbo.P_AddCashIncome #AccountName, 2, NULL, NULL, #Rank1Rewards
;
--------------------------------------------------- PVP Rank #2 - #10 QC distribution via while loop ---------------------------------------------------
USE DNMembership
GO
DECLARE #AccountName nvarchar(50), #CompensationAmt INT, #i int = 0, #RankRewards int
SET #RankRewards = 2
WHILE (#i <= 10) -- BE AWARE IF EDITING
BEGIN
SET #i = #i + 1
SET #AccountName = (SELECT AccountName FROM #TempAccountTable where TotalRank = 1 + #i) -- BE AWARE IF EDITING
EXEC dbo.P_AddCashIncome #AccountName, 2, NULL, NULL, #RankRewards;
END;
-- PVP Rank #11 - #25 distribution via while loop
USE DNMembership
GO
DECLARE #AccountName nvarchar(50), #CompensationAmt INT, #i int = 0, #RankRewards int
SET #RankRewards = 3
WHILE (#i <= 25)
BEGIN
SET #i = #i + 1
SET #AccountName = (SELECT AccountName FROM #TempAccountTable where TotalRank = 10 + #i)
EXEC dbo.P_AddCashIncome #AccountName, 2, NULL, NULL, #RankRewards;
END;
--------------------------------------------------- PVP Rank #26 - #100 QC distribution via while loop ---------------------------------------------------
USE DNMembership
GO
DECLARE #AccountName nvarchar(50), #CompensationAmt INT, #i int = 0, #RankRewards int
SET #RankRewards = 4
WHILE (#i <= 100)
BEGIN
SET #i = #i + 1
SET #AccountName = (SELECT AccountName FROM #TempAccountTable where TotalRank = 25 + #i)
EXEC dbo.P_AddCashIncome #AccountName, 2, NULL, NULL, #RankRewards;
END;
--------------------------------------------------- PVP Mail Rewards #2 - #10 ---------------------------------------------------
USE DNWorld
GO
SET ANSI_NULLS, QUOTED_IDENTIFIER ON
GO
DECLARE
#nvcSenderName nvarchar(50),
#Subject nvarchar(50),
#Content nvarchar(300),
#CharacterName nvarchar(50),
#CoinAmount bigint,
#ItemID1 bigint ,
#ItemID2 bigint ,
#insItemCount1 smallint,
#insItemCount2 smallint,
#LevelItem1 bigint,
#LevelItem2 bigint,
#MailTabCode tinyint,
#i int = 0
WHILE (#i <= 10) -- BE AWARE IF EDITING
BEGIN
SET #i = #i + 1
-- FROM
SET #nvcSenderName = 'PVP Logistics Bot'
-- SUBJECT
SET #Subject = 'Top 10 Player Killers'
-- MESSAGE
SET #Content = 'Outstanding job on maintaining your status as one of the top 10 players throughout Skitzovania.'
-- TARGET CHAR and Loop to desired rank #
SET #CharacterName = (SELECT CharacterName FROM #TempAccountTable where TotalRank = 1 + #i)
-- COPPER
SET #CoinAmount = '0'
-- ITEM ID
SET #ItemID1 = '374341682' -- Goddess Medal
SET #ItemID2 = '335833344' -- Warrior's Trophy
-- QUANTITY
SET #insItemCount1 = '1'
SET #insItemCount2 = '2'
-- ENHANCEMENT LEVEL
SET #LevelItem1 = '0'
SET #LevelItem2 = '0'
-- MAIL TAB TYPE
-- 0 All, 1 Character, 2 Contents, 3 Event, 4 System
SET #MailTabCode = 4
DECLARE
#ItemSerial1 bigint
DECLARE
#ItemSerialfix1 bigint
DECLARE
#inbReceiverCharacterID int
BEGIN
SET #inbReceiverCharacterID = (Select CharacterID from DNWorld.dbo.Characters where CharacterName = #CharacterName)
SET #ItemSerial1 = (SELECT max(ItemSerial) as ItemSerial
FROM dnworld.dbo.MaterializedItems)
SET #ItemSerialfix1 = (#ItemSerial1 + 1)
DECLARE
#ItemSerial2 bigint
DECLARE
#ItemSerialfix2 bigint
SET #ItemSerial2 = (SELECT max(ItemSerial) as ItemSerial
FROM dnworld.dbo.MaterializedItems)
SET #ItemSerialfix2 = (#ItemSerial2 + 1)
EXEC DNWorld.dbo.P_SendSystemMail
#nvcSenderName,
#inbReceiverCharacterID,
3,
4,
#Subject,
#Content,
#CoinAmount,
#ItemSerialfix1,
#ItemID1,
#insItemCount1,
24000,
0,
#LevelItem1,
0,
0,
1,
0,
1,
0,
#ItemSerialfix2,
#itemid2,
#intChannelID = 0,
#intMapID = 0,
#intTotalMailCount = null,
#intNotReadMailCount = 1,
#int7DaysLeftMailCount = null,
#intMailID = null,
#inyMailTabCode = #MailTabCode
END
END
GO
--------------------------------------------------- PVP Mail Rewards #11 - #25 ---------------------------------------------------
USE DNWorld
GO
SET ANSI_NULLS, QUOTED_IDENTIFIER ON
GO
DECLARE
#nvcSenderName nvarchar(50),
#Subject nvarchar(50),
#Content nvarchar(300),
#CharacterName nvarchar(50),
#CoinAmount bigint,
#ItemID1 bigint ,
#ItemID2 bigint ,
#insItemCount1 smallint,
#insItemCount2 smallint,
#LevelItem1 bigint,
#LevelItem2 bigint,
#MailTabCode tinyint,
#i int = 0
WHILE (#i <= 25) -- BE AWARE IF EDITING
BEGIN
SET #i = #i + 1
-- FROM
SET #nvcSenderName = 'PVP Logistics Bot'
-- SUBJECT
SET #Subject = 'Top 25 Player Killers'
-- MESSAGE
SET #Content = 'Outstanding job on maintaining your status as one of the top 25 players throughout Skitzovania.'
-- TARGET CHAR and Loop to desired rank #
SET #CharacterName = (SELECT CharacterName FROM #TempAccountTable where TotalRank = 10 + #i)
-- COPPER
SET #CoinAmount = '0'
-- ITEM ID
SET #ItemID1 = '374341682' -- Goddess Medal
SET #ItemID2 = '335833344' -- Warrior's Trophy
-- QUANTITY
SET #insItemCount1 = '1'
SET #insItemCount2 = '2'
-- ENHANCEMENT LEVEL
SET #LevelItem1 = '0'
SET #LevelItem2 = '0'
-- MAIL TAB TYPE
-- 0 All, 1 Character, 2 Contents, 3 Event, 4 System
SET #MailTabCode = 4
DECLARE
#ItemSerial1 bigint
DECLARE
#ItemSerialfix1 bigint
DECLARE
#inbReceiverCharacterID int
BEGIN
SET #inbReceiverCharacterID = (Select CharacterID from DNWorld.dbo.Characters where CharacterName = #CharacterName)
SET #ItemSerial1 = (SELECT max(ItemSerial) as ItemSerial
FROM dnworld.dbo.MaterializedItems)
SET #ItemSerialfix1 = (#ItemSerial1 + 1)
DECLARE
#ItemSerial2 bigint
DECLARE
#ItemSerialfix2 bigint
SET #ItemSerial2 = (SELECT max(ItemSerial) as ItemSerial
FROM dnworld.dbo.MaterializedItems)
SET #ItemSerialfix2 = (#ItemSerial2 + 1)
EXEC DNWorld.dbo.P_SendSystemMail
#nvcSenderName,
#inbReceiverCharacterID,
3,
4,
#Subject,
#Content,
#CoinAmount,
#ItemSerialfix1,
#ItemID1,
#insItemCount1,
24000,
0,
#LevelItem1,
0,
0,
1,
0,
1,
0,
#ItemSerialfix2,
#itemid2,
#intChannelID = 0,
#intMapID = 0,
#intTotalMailCount = null,
#intNotReadMailCount = 1,
#int7DaysLeftMailCount = null,
#intMailID = null,
#inyMailTabCode = #MailTabCode
END
END
GO
--------------------------------------------------- PVP Mail Rewards #26 - #100 ---------------------------------------------------
USE DNWorld
GO
SET ANSI_NULLS, QUOTED_IDENTIFIER ON
GO
DECLARE
#nvcSenderName nvarchar(50),
#Subject nvarchar(50),
#Content nvarchar(300),
#CharacterName nvarchar(50),
#CoinAmount bigint,
#ItemID1 bigint ,
#ItemID2 bigint ,
#insItemCount1 smallint,
#insItemCount2 smallint,
#LevelItem1 bigint,
#LevelItem2 bigint,
#MailTabCode tinyint,
#i int = 0
WHILE (#i <= 100) -- BE AWARE IF EDITING
BEGIN
SET #i = #i + 1
-- FROM
SET #nvcSenderName = 'PVP Logistics Bot'
-- SUBJECT
SET #Subject = 'Top 100 Player Killers'
-- MESSAGE
SET #Content = 'Outstanding job on maintaining your status as one of the top 100 players throughout Skitzovania.'
-- TARGET CHAR and Loop to desired rank #
SET #CharacterName = (SELECT CharacterName FROM #TempAccountTable where TotalRank = 25 + #i)
-- COPPER
SET #CoinAmount = '0'
-- ITEM ID
SET #ItemID1 = '374341682' -- Goddess Medal
SET #ItemID2 = '335833344' -- Warrior's Trophy
-- QUANTITY
SET #insItemCount1 = '1'
SET #insItemCount2 = '2'
-- ENHANCEMENT LEVEL
SET #LevelItem1 = '0'
SET #LevelItem2 = '0'
-- MAIL TAB TYPE
-- 0 All, 1 Character, 2 Contents, 3 Event, 4 System
SET #MailTabCode = 4
DECLARE
#ItemSerial1 bigint
DECLARE
#ItemSerialfix1 bigint
DECLARE
#inbReceiverCharacterID int
BEGIN
SET #inbReceiverCharacterID = (Select CharacterID from DNWorld.dbo.Characters where CharacterName = #CharacterName)
SET #ItemSerial1 = (SELECT max(ItemSerial) as ItemSerial
FROM dnworld.dbo.MaterializedItems)
SET #ItemSerialfix1 = (#ItemSerial1 + 1)
DECLARE
#ItemSerial2 bigint
DECLARE
#ItemSerialfix2 bigint
SET #ItemSerial2 = (SELECT max(ItemSerial) as ItemSerial
FROM dnworld.dbo.MaterializedItems)
SET #ItemSerialfix2 = (#ItemSerial2 + 1)
EXEC DNWorld.dbo.P_SendSystemMail
#nvcSenderName,
#inbReceiverCharacterID,
3,
4,
#Subject,
#Content,
#CoinAmount,
#ItemSerialfix1,
#ItemID1,
#insItemCount1,
24000,
0,
#LevelItem1,
0,
0,
1,
0,
1,
0,
#ItemSerialfix2,
#itemid2,
#intChannelID = 0,
#intMapID = 0,
#intTotalMailCount = null,
#intNotReadMailCount = 1,
#int7DaysLeftMailCount = null,
#intMailID = null,
#inyMailTabCode = #MailTabCode
END
END
GO
I have created a stored procedure for Save InvoicePayment. When I tried to execute the stored procedure, I get the below error:
Msg 8114, Level 16, State 5, Procedure USP_SaveInvoicePayment_LKO,
Line 0 [Batch Start Line 118] Error converting data type varchar to
numeric.
ALTER PROC Usp_saveinvoicepayment_lko #RECEIPTNO VARCHAR(500),
#INVOICEID BIGINT,
#PayableAmount NUMERIC(10, 2),
#RECEIPTDT DATE,
#PAYMENTMODE VARCHAR(50),
#TRANREF VARCHAR(500),
#USERID BIGINT,
#CHEQUEDATE DATE,
#isValid INT,
#remark VARCHAR(100),
#InvoiceNo VARCHAR(50),
#PaymentRecieved VARCHAR(20),
#PreviousBalance NUMERIC(10, 2),
#ChequeNumber VARCHAR(20),
#PaymentMonth VARCHAR(20),
#PaymentDate DATE,
#CollectorMobile INT,
#Latitude NUMERIC(10, 2),
#Longitude NUMERIC(10, 2),
#RESPONSECODE INT output,
#RESPONSEMESSAGE VARCHAR(255) output,
#IDRESPONSE VARCHAR(200) output
AS
SET nocount ON
BEGIN
--declare #PRJCD varchar(10),
--#KML GEOMETRY ,
--#rowcount int
BEGIN try
--SELECT #PRJCD=PRJCD FROM PRJMST WHERE ID=#PRJID
IF #RECEIPTNO IS NULL
BEGIN
DECLARE #id_out TABLE
(
id VARCHAR(200)
)
--set #ENTRYDATE=getdate()
-- select
convert(varchar,isnull(max(convert(numeric,substring(receiptno,21,50)))+1,1))
from invoicepayment where invoiceid=#invoiceid
INSERT INTO invoicepayment_lko
(receiptno,
invoiceid,
payableamount,
receiptdt,
paymentmode,
trnreference,
userid,
entrydate,
chequedate,
isvalid,
remark,
invoiceno,
paymentrecieved,
previousbalance,
chequenumber,
paymentmonth,
paymentdate,
collectormobile,
latitude,
longitude)
output inserted.receiptno
INTO #id_out
VALUES ( #INVOICENO + '/REC/'
+ (SELECT CONVERT(VARCHAR, Isnull(
Max(CONVERT(NUMERIC, Substring(
receiptno, 21,
50
)))
+ 1, 1))
FROM invoicepayment_lko
WHERE invoiceid = #invoiceid),
#INVOICEID,
#PayableAmount,
#RECEIPTDT,
#PAYMENTMODE,
#TRANREF,
#USERID,
Getdate(),
#CHEQUEDATE,
#isValid,
#remark,
#InvoiceNo,
#PaymentRecieved,
#PreviousBalance,
#ChequeNumber,
#PaymentMonth,
#PaymentDate,
#CollectorMobile,
#Latitude,
#Longitude)
SELECT #IDRESPONSE = id
FROM #id_out
SELECT Ident_current(id)
FROM invoicepayment_lko
UPDATE invoicedetails
SET balanceamt = balanceamt - #PayableAmount
WHERE id = #INVOICEID
END
ELSE
BEGIN
UPDATE invoicepayment_lko
SET chequedate = #CHEQUEDATE,
invoiceid = #INVOICEID,
payableamount = #PayableAmount,
receiptdt = #RECEIPTDT,
paymentmode = #PAYMENTMODE,
trnreference = #TRANREF,
userid = #USERID,
updatedt = Getdate(),
isvalid = #isValid,
remark = #remark,
invoiceno = #InvoiceNo,
paymentrecieved = #PaymentRecieved,
previousbalance = #PreviousBalance,
chequenumber = #ChequeNumber,
paymentmonth = #PaymentMonth,
paymentdate = #PaymentDate,
collectormobile = #CollectorMobile,
latitude = #Latitude,
longitude = #Longitude
WHERE receiptno = #RECEIPTNO
SET #IDRESPONSE = #RECEIPTNO
END
DECLARE #totalPayment NUMERIC(10, 2)
SELECT #totalPayment = Sum(payableamount)
FROM invoicepayment_lko
WHERE invoiceid = #invoiceid
AND isvalid = 1
SELECT #totalPayment,
#invoiceid
END try
BEGIN catch
SELECT #RESPONSECODE = Error_number(),
#RESPONSEMESSAGE = Error_message();
--set #RESPONSEMESSAGE= #prjid;
SELECT #RESPONSECODE,
#RESPONSEMESSAGE
END catch
IF #RESPONSECODE IS NULL
BEGIN
IF #isValid = 0
BEGIN
SET #RESPONSEMESSAGE = 'Payment marked as Invalid'
END
ELSE
BEGIN
SET #RESPONSEMESSAGE = 'Payment created/Updated
Successfully'
END
SET #RESPONSECODE = 200
END
END
--Execution
DECLARE #RESPONSECODE INT = 20,
#RESPONSEMESSAGE VARCHAR(255) = 'Payment Created',
#IDRESPONSE VARCHAR(200) = 'No Response'
EXEC Usp_saveinvoicepayment_lko
NULL,
123,
'87.09',
'2019-07-11',
'Debit',
'test',
12,
'2019-08-11',
1,
'test',
'LP/0819/0000183',
'yES',
'90.09',
'9875',
'7',
'2019-07-18',
988893739,
'28.09',
'76.09',
#RESPONSECODE out,
#RESPONSEMESSAGE out,
#IDRESPONSE out
Please check your input again. As per the parameters passed in procedure
EXEC Usp_saveinvoicepayment_lko
NULL,
123,
'87.09',
'2019-07-11',
'Debit',
'test',
12,
'2019-08-11',
1,
'test',
'LP/0819/0000183',
'yES',
'90.09',
'9875',
'7',
'2019-07-18',
988893739, --- this is one of the reason for your error as you took this as int, but this value will definitly not convert into int.
'28.09',
'76.09',
#RESPONSECODE out,
#RESPONSEMESSAGE out,
#IDRESPONSE out
If you can see for phone number is taken as int and int is not right data type for your field mobile number, either take BigInt or use varchar
My suggestion for mobile number field.
#CollectorMobile BIGINT or VARCHAR(15)
I have a column that gives info on how to parse another column within the same table.The column has the property name and string length of the value that it appears in the next column. Here is how it looks:
PropertyNames PropertyValuesString
SP_PartnerCode:S:0:14:FirstName:S:14:5:LastName:S:19:9: InvestProBase2rogerpatterson
SP_PartnerCode:S:0:14:FirstName:S:14:5:LastName:S:19:7: InvestProBase2AaronSchmidt
SP_PartnerCode:S:0:0:FirstName:S:0:6:LastName:S:6:9: JosephGaultieri
SP_PartnerCode:S:0:14:FirstName:S:14:4:LastName:S:18:9: InvestProBase2ToddEdmondson
SP_PartnerCode:S:0:14:FirstName:S:14:7:LastName:S:21:4: InvestProBase2MichaelLove
I want to separate this into a column per property name, like this:
SP_PartnerCode FirstName LastName
InvestProBase2 roger patterson
InvestProBase2 Aaron Schmidt
Joseph Gaultieri
InvestProBase1 Kevin Lemmon
InvestProBase1 John Switzer
InvestProBase2 bryan abbott
InvestProBase2 Todd Edmondson
InvestProBase2 Michael Love
Is this possible?
You should really normalize your data, was the first thing that came to my mind.
This function parses your data for a given property:
create function Parse(#property nvarchar(4000),
#meta nvarchar(4000), #data nvarchar(4000))
returns nvarchar(4000)
as
begin
set #meta = N':' + #meta
declare #iproperty int, #itype int, #ibegin int, #ilength int, #iend int
set #iproperty = charindex(N':' + #property + N':', #meta)
if #iproperty = 0 return null
set #itype = charindex(N':', #meta, #iproperty + 1)
set #ibegin = charindex(N':', #meta, #itype + 1)
set #ilength = charindex(N':', #meta, #ibegin + 1)
set #iend = charindex(N':', #meta, #ilength + 1)
declare #sbegin nvarchar(5), #slength nvarchar(5)
set #sbegin = substring(#meta, #ibegin + 1, #ilength - #ibegin - 1)
set #slength = substring(#meta, #ilength + 1, #iend - #ilength - 1)
declare #begin int, #length int
set #begin = convert(int, #sbegin)
set #length = convert(int, #slength)
if #length = 0 return null
return substring(#data, #begin + 1, #length)
end
and then SELECT your data
select
dbo.Parse('SP_PartnerCode', PropertyNames, PropertyValuesString) as SP_PartnerCode,
dbo.Parse('FirstName', PropertyNames, PropertyValuesString) as FirstName,
dbo.Parse('LastName', PropertyNames, PropertyValuesString) as LastName
from MyTable
You can use Substring