Insert, Update and Delete using stored Procedure - asp.net

I am trying to Insert, Update, Delete using single stored procedure. Insertion is working correctly but for Deletion it raise error that-
#ID is not a parameter for procedure hrm_Langauges.
I am trying to delete using the id column.
Here is my stored procedure.
ALTER PROCEDURE [dbo].[hrm_Langauges]
(
#Name varchar(120) = 0,
#CreatedOn datetime = 0,
#UpdatedOn datetime = 0,
#CreatedBy bigint = 0,
#UpdatedBy bigint = 0,
#IsDeleted bit = 0,
#status as varchar(50)
)
AS
Declare #ID int;
Select #ID = count(ID) + 1 from [dbo].[Languages]
if(#status = 'Display')
BEGIN
SELECT ID FROM [dbo].[Languages] WHERE Name=#Name
END
else if(#status = 'Add')
BEGIN
IF EXISTS(SELECT Name FROM [dbo].[Languages] WHERE Name = #Name and IsDeleted=0)
Begin
Return 0
End
Else
INSERT INTO [dbo].[Languages](Name,CreatedOn,CreatedBy) VALUES(#Name,#CreatedOn,#CreatedBy)
END
else if(#status = 'Update')
BEGIN
UPDATE [dbo].[Languages] Set Name=#Name,UpdatedOn=#UpdatedOn, UpdatedBy=#UpdatedBy WHERE ID=#ID
END
else if(#status = 'Delete')
BEGIN
UPDATE [dbo].[Languages] Set IsDeleted=#IsDeleted WHERE ID=#ID
END
Where I have to change my sp.
Please help me.

As per your comment,
I am passing id parameter from asp code. Delete record for that Id.
and
Yes I am passing Id from code. Where to change in sp so that it work for that parameter
Your SP parameters don't have #ID, you have declared it locally.
I want you to check if you are trying to passing #Idas parameter to SP. If so, it is cause of error, as SP parameters don't have any parameter named #Id in parameters list.
Solution is to add parameter like #Id INT =0 in parameter.
Also you you have to rename local parameter #Id & all of its usage as this can conflict.
ALTER PROCEDURE [dbo].[hrm_Langauges]
(
#Name varchar(120) = 0,
#CreatedOn datetime = 0,
#UpdatedOn datetime = 0,
#CreatedBy bigint = 0,
#UpdatedBy bigint = 0,
#IsDeleted bit = 0,
#status as varchar(50)
,#Id INT =0 //Add this line
)
AS
Declare #ID_Local int;//Change
Select #ID_Local = count(ID) + 1 from [dbo].[Languages]//change
if(#status = 'Display')
BEGIN
SELECT ID FROM [dbo].[Languages] WHERE Name=#Name
END
else if(#status = 'Add')
BEGIN
IF EXISTS(SELECT Name FROM [dbo].[Languages] WHERE Name = #Name and IsDeleted=0)
Begin
Return 0
End
Else
INSERT INTO [dbo].[Languages](Name,CreatedOn,CreatedBy) VALUES(#Name,#CreatedOn,#CreatedBy)
END
else if(#status = 'Update')
BEGIN
UPDATE [dbo].[Languages] Set Name=#Name,UpdatedOn=#UpdatedOn, UpdatedBy=#UpdatedBy WHERE ID=#ID_Local//change
END
else if(#status = 'Delete')
BEGIN
UPDATE [dbo].[Languages] Set IsDeleted=#IsDeleted WHERE ID=#ID
END

Related

dynamic query showing 'Unclosed quotation mark after the character string '),

i have a stored procedure in which i am getting error 'Unclosed quotation mark after the character string ' having a hard time with the script. please help me to find out what is wrong in my code.
here is my code.
ALTER PROCEDURE [dbo].[usp_Transfer]
#orgid bigint,
#SearchString nvarchar (500) = null,
#LocationId bigint = 0,
#ownerid bigint,
#OrderList varchar(MAX)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.\
SET NOCOUNT ON;
DECLARE #SQL varchar(MAX)
BEGIN
SET #SQL = 'SELECT ProductID = ii.ProductId,
InvItemId = convert(bigint,0),Name = p.Name,
PrimaryImageID = p.PrimaryImageID,ProductNumberLabel = p.ProductNumberLabel,ProductNumber = p.ProductNumber,
category = isnull(c.Name,''),
qty = ISNULL((SUM(ii.[QuantityOnHand]) - SUM(ii.[QuantitySold])), 0.00),
SalePrice= ISNULL(p.SalePrice, 0.00),
EnteredQuantity=(case when (ISNULL((SUM(ii.[QuantityOnHand]) - SUM(ii.[QuantitySold])), 0.00) > 1) then 1.00 else ISNULL((SUM(ii.[QuantityOnHand]) - SUM(ii.[QuantitySold])), 0.00) end)
,Discount=0,u.UnitName,
u.UnitID
FROM dbo.[Inven] ii
Left Join dbo.[Product] p on ii.ProductId = p.ProductId and p.activestatus=1
Left Join dbo.[category] c on p.DefaultCategoryId = c.CategoryId
Left Join dbo.[Unit] u on p.UnitId=u.UnitId and u.Activestatus=1
WHERE p.OrganizationID = #orgid
AND ii.InventoryID IN(1634)
AND ii.ActiveStatus = 1
AND p.ActiveStatus = 1
AND p.IsDisabled = 0
And p.CanSale = 1
AND ii.InventoryID IN (' + #OrderList + ')
group by ii.ProductId, p.Name, p.PrimaryImageID, p.ProductNumberLabel, p.ProductNumber, c.Name,p.SalePrice,u.unitname,u.UnitID
having ISNULL((SUM(ii.[QuantityOnHand]) - SUM(ii.[QuantitySold])), 0) > 0
Order by p.ProductNumber, p.Name, c.Name '
--EXEC(#SQL)
PRINT(#SQL)
END
END
Two things of note.
First, does #OrderList contain any quotes?
Second, this line:
...' WHERE p.OrganizationID = #orgid '
Should be:
....'WHERE p.OrganizationID = ' + #orgid + '...'
The easy way to test if either of these are the cause of the problem is to comment both out, run it and see if it works, if it does then comment them in one at a time to see which one gives you the error.
Finally, you could rewrite this query and avoid using a dynamic query at all. I guess looking at the query you have done it because of the IN (' + #OrderList + ') clause. These posts might help you rework that section:
Parameterize an SQL IN clause
SQL Server - In clause with a declared variable
Update your SP as below:
Note: there are so many errors if solve one like quotation mark, declare variable #orgid and then conversion error
Your initial error due to : category = isnull(c.Name,''), replace it with category = isnull(c.Name,'''')
alter PROCEDURE [dbo].[usp_Transfer]
#orgid bigint=1,
#SearchString nvarchar (500) = null,
#LocationId bigint = 0,
#ownerid bigint=1,
#OrderList varchar(MAX)='1'
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.\
SET NOCOUNT ON;
DECLARE #SQL varchar(MAX)
BEGIN
SET #SQL = 'SELECT ProductID = ii.ProductId,
InvItemId = convert(bigint,0),Name = p.Name,
PrimaryImageID = p.PrimaryImageID,ProductNumberLabel = p.ProductNumberLabel,ProductNumber = p.ProductNumber,
category = isnull(c.Name,''''),
qty = ISNULL((SUM(ii.[QuantityOnHand]) - SUM(ii.[QuantitySold])), 0.00),
SalePrice= ISNULL(p.SalePrice, 0.00),
EnteredQuantity=(case when (ISNULL((SUM(ii.[QuantityOnHand]) - SUM(ii.[QuantitySold])), 0.00) > 1) then 1.00 else ISNULL((SUM(ii.[QuantityOnHand]) - SUM(ii.[QuantitySold])), 0.00) end)
,Discount=0,u.UnitName,
u.UnitID
FROM dbo.[Inven] ii
Left Join dbo.[Product] p on ii.ProductId = p.ProductId and p.activestatus=1
Left Join dbo.[category] c on p.DefaultCategoryId = c.CategoryId
Left Join dbo.[Unit] u on p.UnitId=u.UnitId and u.Activestatus=1
WHERE p.OrganizationID = '+CAST(#orgid AS VARCHAR(10))+'
AND ii.InventoryID IN(1634)
AND ii.ActiveStatus = 1
AND p.ActiveStatus = 1
AND p.IsDisabled = 0
And p.CanSale = 1
AND ii.InventoryID IN (' + #OrderList + ')
group by ii.ProductId, p.Name, p.PrimaryImageID, p.ProductNumberLabel, p.ProductNumber, c.Name,p.SalePrice,u.unitname,u.UnitID
having ISNULL((SUM(ii.[QuantityOnHand]) - SUM(ii.[QuantitySold])), 0) > 0
Order by p.ProductNumber, p.Name, c.Name '
EXEC(#SQL)
PRINT(#SQL)
END
END

How can I write two update queries in single stored procedure in SQL Server 2008

I have a table that contains a few columns bound to a gridview.
In that gridview, I have an edit option to update the columns. In that situation I need to write a two update stored procedures that means I select all columns expect AudiotoName, select another columns all columns are update to raise one update query but when I select table in that have AudiotoName column that only edit to select that column it will raise second update stored procedure. I tried but it not properly working can anyone help me out.
My code:
ALTER PROCEDURE up_file
(#ModuleID int,
#SubjectID int,
#Physician varchar(500) = '',
#AuditoName varchar(300) = '',
#AuditoType varchar(50) = '',
#AudioPath varchar(2000) = '',
#BaseDocumentName varchar(500) = '',
#BaseDocumentPath varchar(2000) = '',
#Createddate datetime,
#CreatedBy varchar(200) = '')
AS
BEGIN
IF #AuditoName = 'true' //select AuditoName column only raise this update query
BEGIN
UPDATE SubjectItems
SET ModuleID = #ModuleID,
SubjectID = #SubjectID,
Physician = '#Physician',
AuditoName = '#AuditoName',
AuditoType = '#AuditoType',
AudioPath ='#AudioPath',
BaseDocumentName = '#BaseDocumentName',
BaseDocumentPath = '#BaseDocumentPath'
WHERE AuditoName = #AuditoName
END
BEGIN //normal fields select raise this update query
UPDATE SubjectItems
SET ModuleID = #ModuleID,
SubjectID = #SubjectID,
Physician = '#Physician',
AuditoName = '#AuditoName',
AuditoType = '#AuditoType',
AudioPath ='#AudioPath',
BaseDocumentName = '#BaseDocumentName',
BaseDocumentPath = '#BaseDocumentPath'
WHERE ModuleID = #ModuleID
END
END
Can anyone help me out?
The problem in your query is that, even if #AuditoName is true, the lower update query is running. This will re-update the table SubjectItems. You can use if...else block instead, like below:
ALTER PROCEDURE up_file
(#ModuleID int,
#SubjectID int,
#Physician varchar(500) = '',
#AuditoName varchar(300) = '',
#AuditoType varchar(50) = '',
#AudioPath varchar(2000) = '',
#BaseDocumentName varchar(500) = '',
#BaseDocumentPath varchar(2000) = '',
#Createddate datetime,
#CreatedBy varchar(200) = '')
AS
BEGIN
IF #AuditoName = 'true' //select AuditoName column only raise this update query
BEGIN
UPDATE SubjectItems
SET ModuleID = #ModuleID,
SubjectID = #SubjectID,
Physician = '#Physician',
AuditoName = '#AuditoName',
AuditoType = '#AuditoType',
AudioPath ='#AudioPath',
BaseDocumentName = '#BaseDocumentName',
BaseDocumentPath = '#BaseDocumentPath'
WHERE AuditoName = #AuditoName
END
ELSE
BEGIN //normal fields select raise this update query
UPDATE SubjectItems
SET ModuleID = #ModuleID,
SubjectID = #SubjectID,
Physician = '#Physician',
AuditoName = '#AuditoName',
AuditoType = '#AuditoType',
AudioPath ='#AudioPath',
BaseDocumentName = '#BaseDocumentName',
BaseDocumentPath = '#BaseDocumentPath'
WHERE ModuleID = #ModuleID
END
END

How to separate (split) string with comma in SQL Server stored procedure

I have a checkboxlist. The selected (checked) items are stored in List<string> selected.
For example, value selected is monday,tuesday,thursday out of 7 days
I am converting List<> to a comma-separated string, i.e.
string a= "monday,tuesday,thursday"
Now, I am passing this value to a stored procedure as a string. I want to fire query like:
Select *
from tblx
where days = 'Monday' or days = 'Tuesday' or days = 'Thursday'`
My question is: how to separate string in the stored procedure?
If you pass the comma separated (any separator) string to store procedure and use in query so must need to spit that string and then you will use it.
Below have example:
DECLARE #str VARCHAR(500) = 'monday,tuesday,thursday'
CREATE TABLE #Temp (tDay VARCHAR(100))
WHILE LEN(#str) > 0
BEGIN
DECLARE #TDay VARCHAR(100)
IF CHARINDEX(',',#str) > 0
SET #TDay = SUBSTRING(#str,0,CHARINDEX(',',#str))
ELSE
BEGIN
SET #TDay = #str
SET #str = ''
END
INSERT INTO #Temp VALUES (#TDay)
SET #str = REPLACE(#str,#TDay + ',' , '')
END
SELECT *
FROM tblx
WHERE days IN (SELECT tDay FROM #Temp)
Try this:
CREATE FUNCTION [dbo].[ufnSplit] (#string NVARCHAR(MAX))
RETURNS #parsedString TABLE (id NVARCHAR(MAX))
AS
BEGIN
DECLARE #separator NCHAR(1)
SET #separator=','
DECLARE #position int
SET #position = 1
SET #string = #string + #separator
WHILE charindex(#separator,#string,#position) <> 0
BEGIN
INSERT into #parsedString
SELECT substring(#string, #position, charindex(#separator,#string,#position) - #position)
SET #position = charindex(#separator,#string,#position) + 1
END
RETURN
END
Then use this function,
Select *
from tblx
where days IN (SELECT id FROM [dbo].[ufnSplit]('monday,tuesday,thursday'))
try this
CREATE FUNCTION Split
(
#delimited nvarchar(max),
#delimiter nvarchar(100)
) RETURNS #t TABLE
(
-- Id column can be commented out, not required for sql splitting string
id int identity(1,1), -- I use this column for numbering splitted parts
val nvarchar(max)
)
AS
BEGIN
declare #xml xml
set #xml = N'<root><r>' + replace(#delimited,#delimiter,'</r><r>') + '</r></root>'
insert into #t(val)
select
r.value('.','varchar(max)') as item
from #xml.nodes('//root/r') as records(r)
RETURN
END
GO
usage:
select * from tblx where days in (select val from dbo.split('monday,tuesday,thursday',','))
I think you want this
SELECT * FROM tblx where days in ('Monday','Tuesday','Thursday')
you can get it like this:
var a = "monday,tuesday,thursday";
var sql = string.Format("Select * from tblx where days IN ('{0}')", string.Join("','",a.Split(new[] {','})));
I face the same problem, and i try all the way but not get expected solution. Finally i did like follow. Try it hope it will work...
create Function [dbo].[Split]
(
#RowData NVARCHAR(MAX),
#SplitOn NVARCHAR(5)
)
RETURNS #RtnValue TABLE
(
Id INT IDENTITY(1,1),
Data NVARCHAR(100)
)
AS
BEGIN
DECLARE #Cnt INT
SET #Cnt = 1
WHILE (Charindex(#SplitOn,#RowData)>0)
BEGIN
INSERT INTO #RtnValue (data)
SELECT Data = ltrim(rtrim(Substring(#RowData,1,Charindex(#SplitOn,#RowData)-1)))
SET #RowData = Substring(#RowData,Charindex(#SplitOn,#RowData)+1,len(#RowData))
SET #Cnt = #Cnt + 1
END
INSERT INTO #RtnValue (data)
SELECT Data = ltrim(rtrim(#RowData))
RETURN
END
And in the store procedure put the code like that.
select #ActualTarget= count(*) from UpdateVisitDetails where CreatedBy IN (SELECT [DATA] FROM [dbo].[Split](#AllDATS,',' ))
I have same problem. I tried this.. and this was properly run
ALTER FUNCTION [dbo].[Split]
(
#List varchar(max),
#SplitOn nvarchar(5)
)
RETURNS #RtnValue table
(
Id int identity(1,1),
Value nvarchar(max)
)
AS
BEGIN
IF (len(#List) <=0)
Begin
Return
End
While (Charindex(#SplitOn,#List)>0)
Begin
Insert Into #RtnValue (value)
Select
Value = ltrim(rtrim(Substring(#List,1,Charindex(#SplitOn,#List)-1)))
Set #List = Substring(#List,Charindex(#SplitOn,#List)+len(#SplitOn),len(#List))
End
Insert Into #RtnValue (Value)
Select Value = ltrim(rtrim(#List))
Return
END
Run :
SELECT * FROM dbo.Split('Apple,Banana,Mango',',')
Output:

Asp.net(c#) Custom Paging With Stored Procedure - Bad Performance During Pagination

I have a asp:GridView with datasource like List
I added custom paging, using a procedure, when i use the procedure in MS SERVER Management
Studio its performance is fast, as soon as i try it in asp.net, performance is awful during
pagination.
The 1st step (when the gridview fills) is very fast, but when i am starting to paginate,
the performance kills, i am waiting 5-25 seconds for passing to the next page.
Dear all, what must i do to solve this problem, will you help me ?
HERE IS THE STORED PROCEDURE
CREATE PROCEDURE [sp_QS]
#startRowIndex INT,
#maximumRows INT,
#afterWhere NVARCHAR(MAX),
#sortBy NVARCHAR(MAX),
#totalRows INT OUT
AS
SET NOCOUNT ON;
DECLARE #P NVARCHAR(MAX), #Q1 NVARCHAR(MAX), #Q2 NVARCHAR(MAX)
DECLARE #first_id INT
SET #startRowIndex = (#startRowIndex - 1) * #maximumRows
SET #Q1 = 'query part 1'
SET #Q2 = 'query part 2'
IF #startRowIndex = 0
BEGIN
SET #startRowIndex = 1
END
SET ROWCOUNT #startRowIndex
SET #P = 'SET NOCOUNT ON; DECLARE #out INT SELECT #out = id FROM table1 ' + #Q2 + '
WHERE ' + #afterWhere + ' SELECT #out'
IF OBJECT_ID('tempdb..#t1','u') IS NOT NULL
BEGIN
DROP TABLE #t1
END
CREATE TABLE #t1 (col INT)
INSERT #t1 EXEC(#P)
SELECT #first_id = col FROM #t1
DROP TABLE #t1
--SELECT #first_id AS FFFF --PRINT #first_id
SET ROWCOUNT #maximumRows
SET #P = 'SET NOCOUNT ON;' + 'SELECT ' + #Q1 + ' FROM table ' + #Q2 + ' WHERE (id >=' +
CAST(#first_id AS NVARCHAR(60)) + ') AND (' + #afterWhere + ') ' + #sortBy
EXEC(#P)
SET ROWCOUNT 0
-- GET THE TOTAL ROWS
IF #startRowIndex = 1
BEGIN
SET #P = 'SET NOCOUNT ON;' + 'SELECT COUNT(id) FROM table1 ' + #Q2 + ' WHERE ' +
#afterWhere
IF OBJECT_ID('tempdb..#t2','u') IS NOT NULL
BEGIN
DROP TABLE #t2
END
CREATE TABLE #t2 (col INT)
INSERT #t2 EXEC (#P)
SELECT #totalRows = col FROM #t2
DROP TABLE #t2
SELECT #totalRows AS QueryResultRowCount
END
GO
AND HERE IS THE CODE IN ASP.NET(WITH C#)
private void BindData()
{
string connectionString = "Server=localhost;" +
"Database=Northwind;Trusted_Connection=true";
SqlConnection myConnection = new SqlConnection(connectionString);
SqlCommand myCommand = new SqlCommand("usp_GetProducts",
myConnection);
myCommand.CommandType = CommandType.StoredProcedure;
myCommand.Parameters.AddWithValue("#startRowIndex",
currentPageNumber);
myCommand.Parameters.AddWithValue("#maximumRows", PAGE_SIZE);
myCommand.Parameters.Add("#totalRows", SqlDbType.Int, 4);
myCommand.Parameters["#totalRows"].Direction =
ParameterDirection.Output;
SqlDataReader sqlReader = myCommand.ExecuteReader();
while(sqlReader.Read())
{
// filling List<> object to bind to gridview as datasource
}
...
}
I have to buttons 'next' and 'prvious', pressing these buttons, i am changing
currentPageNumber with + or - 1, calling BindData() method after it.
Thanks in advance
That's an SQL against the AdventureWorks database from SQL Server 2005 samples:
DECLARE
#FirstRow int,
#LastRow int,
#Sorting varchar(50);
Declare #SelectClause nvarchar(max),
#Params nvarchar(MAX);
SELECT #FirstRow = 1, #LastRow = 10;
SELECT #SelectClause = 'WITH CTE AS (
SELECT
ROW_NUMBER() OVER ( ORDER BY ' + COALESCE(#Sorting, 'SalesOrderID ASC') + ' ) AS RowNumber,
COUNT(*) OVER() AS TotalRows,
SalesOrderID,
OrderDate,
DueDate,
CASE OnlineOrderFlag WHEN 1 THEN ''Yes'' ELSE ''No'' END as OnlineOrderFlagString
FROM
Sales.SalesOrderHeader
WHERE
SubTotal > 100)
SELECT * FROM CTE WHERE RowNumber >= #FirstRow AND RowNumber < #LastRow',
#Params = '#FirstRow int, #LastRow int';
exec sp_executesql
#statement = #SelectClause,
#params = #Params,
#FirstRow = #FirstRow,
#LastRow = #LastRow;
After you have execute query you can fetch total rows value from first row if exists. Note, that if you must provide ability to sort by computed columns like the OnlineOrderFlagString, the query will become bit more complex:
DECLARE
#FirstRow int,
#LastRow int,
#Sorting varchar(50);
Declare #SelectClause nvarchar(max),
#Params nvarchar(MAX);
SELECT #FirstRow = 1, #LastRow = 10, #Sorting = 'OnlineOrderFlagString ASC'
SELECT #SelectClause = 'WITH CTE_1 AS (
SELECT
SalesOrderID,
OrderDate,
DueDate,
CASE OnlineOrderFlag WHEN 1 THEN ''Yes'' ELSE ''No'' END as OnlineOrderFlagString
FROM
Sales.SalesOrderHeader
WHERE
SubTotal > 100),
CTE_2 AS (
SELECT
ROW_NUMBER() OVER ( ORDER BY ' + COALESCE(#Sorting, 'SalesOrderID ASC') + ' ) AS RowNumber,
COUNT(*) OVER() AS TotalRows,
SalesOrderID,
OrderDate,
DueDate,
OnlineOrderFlagString
FROM
CTE_1
)
SELECT * FROM CTE_2 WHERE RowNumber >= #FirstRow AND RowNumber < #LastRow',
#Params = '#FirstRow int, #LastRow int';
exec sp_executesql
#statement = #SelectClause,
#params = #Params,
#FirstRow = #FirstRow,
#LastRow = #LastRow;

insert statement conflicted with the foreign key constraint?

my stored procedure is-
CREATE PROCEDURE [dbo].[usp_SetMenu](
#locationId BIGINT,
#menuId BIGINT = NULL,
#name VARCHAR(100) = NULL,
#taxable BIT = NULL,
#type VARCHAR(100) = NULL,
#dateFrom DATETIME = NULL,
#dateTo DATETIME = NULL,
#timeFrom VARCHAR(10) = NULL,
#timeTo VARCHAR(10) = NULL,
#price MONEY = NULL,
#discountPerc FLOAT = NULL,
#discTimeFrom VARCHAR(10) = NULL,
#discTimeTo VARCHAR(10) = NULL,
#textcolor varchar(10) = null,
#bodycolor varchar(10) = null,
#createdBy BIGINT = NULL,
#createdOn DATETIME = NULL,
#modifiedBy BIGINT = NULL,
#modifiedOn DATETIME = NULL,
#menuProductsXML NTEXT = NULL ,
#IsCopy VARCHAR (10) = NULL,
#CopyMenuId BIGINT = NULL,
#menuTaxXML NTEXT = NULL ,
#menuExists INT = NULL OUTPUT,
#newMenuId INT = NULL OUTPUT
)
AS
SET NOCOUNT ON
---------------------------------------------------------------------
-- Declarations of variables
---------------------------------------------------------------------
DECLARE #ptrHandle INT
---------------------------------------------------------------------
-- initialize variables
---------------------------------------------------------------------
---------------------------------------------------------------------
-- get the data
---------------------------------------------------------------------
IF(#menuId IS NULL) -- If menuid is null then create a new record
BEGIN
select #menuExists = count('x') from tblMenu
where [name] = #name and isDeleted = 0 and locationid=#locationId
if #menuExists > 0
Return
INSERT INTO tblMenu
(locationid
,[name]
,[type]
,taxable
,datefrom
,dateto
,timefrom
,timeto
,price
,discountperc
,disctimefrom
,disctimeto
,bodycolor
,textcolor
,createdby
,createdon)
VALUES
(#locationId
,#name
,#type
,#taxable
,#dateFrom
,#dateTo
,#timeFrom
,#timeTo
,#price
,#discountPerc
,#discTimeFrom
,#discTimeTo
,#bodycolor
,#textcolor
,#createdBy
,#createdOn)
SET #menuId = ##IDENTITY
END
ELSE -- If menuid is not null then update that record
select #menuExists = count('x') from tblMenu
where [name] = #name and MenuId <> #menuId and isDeleted = 0 and locationid=#locationId
if #menuExists > 0
Return
UPDATE tblMenu
SET locationid = #locationId
,[name] = #name
,[type] = #type
,taxable = #taxable
,datefrom = #dateFrom
,dateto = #dateTo
,timefrom = #timeFrom
,timeto = #timeTo
,price = #price
,discountperc = #discountPerc
,disctimefrom = #discTimeFrom
,disctimeto = #discTimeTo
,bodycolor = #bodycolor
,textcolor = #textcolor
,modifiedby = #modifiedBy
,modifiedon = #modifiedOn
WHERE menuid = #menuId
-- if menu product collection is passed then insert new records
IF(#menuProductsXML IS NOT NULL)
BEGIN
-- Clearing the old menu products and inserting new ones
DELETE tblMenuProduct WHERE menuid = #menuId
EXEC sp_xml_preparedocument #ptrHandle OUTPUT, #menuProductsXML
INSERT INTO tblMenuProduct
(menuid
,productid
,categoryid
,productprice
,createdby
,createdon)
SELECT #menuId,
ProductId,
CategoryId,
ProductPrice,
#createdBy,
#createdOn
FROM OPENXML (#ptrHandle, '/ArrayOfMenuProductEntity/MenuProductEntity', 2)
WITH(ProductId BIGINT,CategoryId BIGINT, ProductPrice MONEY)
END
if(#IsCopy = 'True')
Begin
INSERT INTO tblMenuProduct
(menuid
,productid
,categoryid
,productprice
,createdby
,createdon)
Select #menuId,productid,categoryid,productprice,#createdBy,#createdOn
From tblMenuProduct where menuid = #CopyMenuId
SET #newMenuId = #menuId
End
IF(#menuTaxXML IS NOT NULL)
BEGIN
DELETE tblMenuTaxClass WHERE menuid = #menuId
EXEC sp_xml_preparedocument #ptrHandle OUTPUT, #menuTaxXML
INSERT INTO tblMenuTaxClass
(menuid
,taxclassid
)
SELECT #menuId,
TaxClassId
FROM OPENXML (#ptrHandle, '/ArrayOfTaxClassEntity/TaxClassEntity', 2)
WITH(TaxClassId BIGINT)
END
---------------------------------------------------------------------
-- exit the sproc
---------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------------------
SET NOCOUNT OFF
END
Exception:insert statement conflicted with the foreign key constraint
Why I am getting this exception and how can I fix this?
The primary key value wont be there.you are trying to insert a Foreign key value to the table where corresponding PK wont be there.
table1
ID(PK)
1
2
3
table2
ID1(PK) ID(FK)
1 1
2 1
3 4// Error not there in PK table

Resources