Hello i have the following query with a transaction in a try catch block and i rollback transaction on the catch block if fails. Problem is that I am creating a temporary table and i don't know how to handle it with a transaction. So how can I safely get rid of temporary table in this situation? I tried to add it on catch block but i'm not sure if this is a good practice
ALTER PROCEDURE GetDataForNewListaAbastecimento
#UAP NVARCHAR(20),
#ColaboradorId INT
AS
BEGIN
DECLARE #TransactionName nvarchar(20) = 'GetDataForNewListaAbastecimento'
DECLARE #Status INT
DECLARE #CurrentWeekDay INT
SET DATEFIRST 1
SET #CurrentWeekDay = DATEPART (WEEKDAY, GETDATE()) - 1
CREATE TABLE #tempTable
(
Id INT PRIMARY KEY,
Referencia NVARCHAR(15),
UAP NVARCHAR(20),
ConsumoWeek01 FLOAT,
ConsumoWeek02 FLOAT,
Stock INT,
QtdPecasPorCaixa INT
UNIQUE (Id)
)
BEGIN TRY
BEGIN TRAN #TransactionName
DECLARE #SQL NVARCHAR(MAX)
SELECT #SQL = 'INSERT INTO #tempTable
SELECT
Id,
Referencia,
UAP,
ConsumoWeek01 AS ConsumoWeek01,
ConsumoWeek02,
CASE
WHEN Stock IS NULL THEN 0
ELSE
Stock
END AS Stock,
QtdPecasPorCaixa
FROM OPENQUERY(MACPAC,
''WITH maxFornecedorByDate AS
(
SELECT
YDA3REP.A3ARCD,
YDA3REP.A3D5CD,
ROW_NUMBER() OVER ( PARTITION BY YDA3REP.A3D5CD ORDER BY YDA3REP.A3A3DT DESC) AS Number
FROM
AUTO.YSACHAPOR.YDA3REP YDA3REP
)
SELECT
ROW_NUMBER() OVER(ORDER BY A.RH6001 ASC) AS Id,
A.RH6001 as Referencia,
A.RH6002 as UAP,
A.RH6030 as ConsumoWeek01,
A.RH6031 as ConsumoWeek02,
IC130M.LLBLT1 as Stock,
M.AUQCON AS QtdPecasPorCaixa
FROM AUTO.D805DATPOR.TRP060H AS A
LEFT JOIN AUTO.D805DATPOR.IC130M IC130M
ON A.RH6001 = IC130M.LLPPN AND
IC130M.LLSTLC =
CASE A.RH6002
WHEN ''''UAP1'''' THEN ''''M1''''
WHEN ''''UAP2'''' THEN ''''M2''''
WHEN ''''UAP3'''' THEN ''''M3''''
WHEN ''''UAP4'''' THEN ''''M4''''
WHEN ''''UAP5'''' THEN ''''M5''''
WHEN ''''UAP6'''' THEN ''''M6''''
WHEN ''''UAPP'''' THEN ''''PROTOS''''
WHEN ''''EXT'''' THEN ''''EXTR''''
END
LEFT JOIN
(
SELECT
YDAUREP.AUD5CD,
YDAUREP.AUQCON
FROM maxFornecedorByDate F
join AUTO.YSACHAPOR.YDAUREP YDAUREP
ON F.A3ARCD = YDAUREP.AUARCD
AND F.A3D5CD = YDAUREP.AUD5CD
WHERE F.Number = 1 AND YDAUREP.AUD5CD LIKE ''''M%''''
AND YDAUREP.AUD5CD NOT LIKE ''''%P%''''
AND YDAUREP.AUA0NB > 1
AND YDAUREP.AUG6ST= ''''O''''
) M
ON M.AUD5CD = A.RH6001
WHERE A.RH6001 Not Like ''''FS%''''
AND A.RH6030 <> 0
AND A.RH6002 = ''''' + #UAP + ''''' '')'
EXEC sp_executesql #SQL
INSERT INTO hListasAbastecimento (UAP,DataCriacao,ColaboradorId) VALUES (#UAP,GETDATE(),#ColaboradorId)
INSERT INTO
hReferenciasAbastecimento
(
Referencia,
QtdAbastecimento,
QtdCaixas,
QtdPecasPorCaixa,
ListaAbastecimentoId
)
SELECT
C.Id,
C.Referencia,
( T.ConsumoWeek01 / ( ( P.NumDias - #CurrentWeekDay ) * P.NumPAB )) * P.AlcanceAbastecimento AS QtdAbastecimento,
T.QtdPecasPorCaixa,
CASE
WHEN ((T.ConsumoWeek01 / ( ( P.NumDias - #CurrentWeekDay ) * P.NumPAB )) * P.AlcanceAbastecimento) / NULLIF(T.QtdPecasPorCaixa,0) IS NULL THEN NULL
ELSE
CAST( CEILING(((T.ConsumoWeek01 / ( ( P.NumDias - #CurrentWeekDay ) * P.NumPAB )) * P.AlcanceAbastecimento) / T.QtdPecasPorCaixa ) AS INT)
END AS QtdCaixas,
SCOPE_IDENTITY()
FROM
#tempTable T
INNER JOIN hParametros P
ON P.Referencia = T.Referencia
AND P.UAP = #UAP
INNER JOIN hConsumos C
ON C.Referencia = P.Referencia
AND C.UAP = #UAP
WHERE T.Stock < ( T.ConsumoWeek01 / ( ( P.NumDias - #CurrentWeekDay ) * P.NumPAB )) * P.QtdMin
ORDER BY QtdAbastecimento DESC
COMMIT TRANSACTION #TransactionName
DROP TABLE #tempTable
-- Success, Lista de abastecimento foi criada sem errors --
SELECT #Status = 200
RETURN #Status
END TRY
BEGIN CATCH
IF ##TRANCOUNT > 0
ROLLBACK TRAN #TransactionName
DROP TABLE #tempTable
SELECT
ERROR_NUMBER() AS ErrorNumber,
ERROR_STATE() AS ErrorState,
ERROR_SEVERITY() AS ErrorSeverity,
ERROR_PROCEDURE() AS ErrorProcedure,
ERROR_LINE() AS ErrorLine,
ERROR_MESSAGE() AS ErrorMessage;
-- Erro, Nao foi possivel criar lista de abastecimento, verificar dynamic query --
SELECT #Status = 400
RETURN #Status
END CATCH
END
EDIT
I'm calling the SP from an Asp .NET Core application with Entity Framework Core
await _context.Database
.ExecuteSqlCommandAsync("EXEC #Status = GetDataForNewListaAbastecimento #UAP, #ColaboradorId", #params);
try add this:
IF OBJECT_ID('tempdb..#Results') IS NOT NULL DROP TABLE #Results
(Replace Name your temp table #Result)
Related
I am trying to update a table using table type parameter. Currently I am using the below query. But I would like to perform update in batches having batch size as one of the parameters. Kindly help.
ALTER PROCEDURE UPDATEStatus
#Ids int ,
#numbers TypeofNumbers readonly,
#Status char(2),
#nname varchar(50),
AS
BEGIN
BEGIN TRY
update e
set
e.status = #Status,
e.user =#nname,
e.time = GETDATE()
from detailtable e
join #numbers en on en.ID =e.ID
where e.oddIDs = #Ids
I tried to do in a single update but I wanted to do in sets or batches one by one. say 100 records first and then next 100 records until all are done
You can use something like this to do your update in batches:
CREATE OR ALTER PROCEDURE UPDATEStatus
#Ids INT,
#numbers TypeOfNumbers READONLY,
#Status CHAR(2),
#nname VARCHAR(50)
AS
BEGIN
DECLARE #UpdatedRows INT;
DECLARE #Skip INT = 0;
DECLARE #BatchSize INT = 100;
WHILE ISNULL(#UpdatedRows, 1) > 0
BEGIN
WITH CTE
AS (SELECT *
FROM #numbers AS n
ORDER BY n.ID OFFSET #Skip * #BatchSize ROWS FETCH NEXT #BatchSize ROWS ONLY)
UPDATE e
SET
e.[Status] = #Status,
e.[User] = #nname,
e.[time] = GETDATE()
FROM CTE AS en
JOIN detailtable e ON en.ID = e.ID;
SET #UpdatedRows = ##ROWCOUNT;
SET #Skip = #Skip + 1;
END;
END;
GO
Next time please also provide scripts for the DDL and some testdata.
I am getting this error when I'm trying to getting data with the entity framework from the stored procedure.
Note: This stored procedure working fine when running it in the SQL server but throws an exception in the Entity framework.
The data reader is incompatible with the specified 'BuyMediaModel.GetSpendBreakdownofBuyer_Result'. A member of the type, 'Impressions', does not have a corresponding column in the data reader with the same name.
Here is my sp code.
ALTER Procedure [dbo].[GetSpendBreakdownofBuyer]
-- exec GetSpendBreakdownofBuyer '134', '2020'
#BuyerID varchar(100),
#Year varchar(20)
AS
BEGIN
SET FMTONLY OFF
SELECT
CASE WHEN
s.MediaType='Radio'
THEN 'Radio'
WHEN
s.MediaType='Newspaper' or s.MediaType='Magazine'
THEN 'Print'
WHEN
s.MediaType='TV'
THEN 'TV'
WHEN
s.MediaType='Podcast'
THEN 'Podcast'
WHEN
s.MediaType='OOH'
THEN 'OOH'
WHEN
s.MediaType='Digital'
THEN 'Digital'
ELSE 'Other'
END AS 'MediaType',
0 as Impressions,
Convert(char(3), od.AdvertisingDate, 0) as 'Month',
SUM(od.Price) as 'Budget_Spent'
INTO
#TempBreakdown
FROM
tblOrder o
JOIN
tblOrderDetail od
ON
o.Order_ID = od.Order_ID
JOIN
tblMediaSeller s
ON
s.MediaSeller_ID =od.Seller_ID
WHERE
o.Buyer_ID in (select cast(item as int) from dbo.SplitString(#BuyerID) )
AND YEAR(od.AdvertisingDate)=#Year
AND od.Status in ('Ordered','Approved')
GROUP BY
Convert(char(3), od.AdvertisingDate, 0),
s.MediaType
UNION
SELECT
'Other' as Mediatype,
0 as Impressions,
[Month],
Sum(BudgetSpent)
FROM
tblBudgetSpent
WHERE
Buyer_ID in (select cast(item as int) from dbo.SplitString(#BuyerID) )
AND [Year]=#Year
GROUP BY
[Month]
SELECT
SUM(Budget_Spent) AS Total,
--0 as Impressions,
[month]
INTO
#TempTotal
FROM
#TempBreakdown
GROUP BY
[month]
SELECT
b.MediaType,
0 as Impressions,
--CASE WHEN
-- t.Total <> 0
-- THEN((b.Budget_Spent/t.Total)*100)
-- ELSE
-- 0 END AS budget_spent,
b.Budget_Spent,
b.Month
FROM
#TempBreakdown b
JOIN
#TempTotal t
ON
b.Month=t.Month
UNION
SELECT
'Sales',
0 as Impressions,
Sales,
[Month]
FROM
tblSalesFigure
WHERE
BuyerID in (select cast(item as int) from dbo.SplitString(#BuyerID) )
AND Year=#Year
UNION
SELECT
'Impressions',
Impressions as Impressions,
0 ,
[Month]
FROM
tblMatrics
WHERE
Buyer_ID in (select cast(item as int) from dbo.SplitString(#BuyerID) )
AND Year=#Year
END
How can I select information from tables from many bases in one result. My idea is to put them in DataTable and show them in DataGrid.
Here is query:
exec sp_msforeachdb 'use ?; IF ''?'' <> ''master'' AND ''?'' <> ''model'' AND ''?'' <> ''msdb'' AND ''?'' <> ''tempdb'' AND ''?'' <> ''addresses'' AND ''?'' <> ''ikamebeldizain'' AND ''?'' <> ''new2'' AND ''?'' <> ''sample'' AND ''?'' <> ''sitedatabase'' AND ''?'' <> ''StudentsTeachersTest'' AND ''?'' <> ''MicroinvestDatabasesCatalog'' select * from dbo.system;'
When I try with this query in dataGrid i have just one line (first result).
To append multiple result sets in SQL, you need to have identical results structure (ie: the same columns are returned in the same order) and to tell SQL to bolt them together with a union all (Using just union will remove duplicate rows). To do this across different databases, assuming they are on the same server you can just reference the database in your query:
select *
from Database1.dbo.system
union all
select *
from Database2.dbo.system
If you are trying to do this across a dynamic set of databases, you will only be able to do this with dynamic SQL, which will output the above statement based on a list of databases provided earlier in the script, which you can then execute.
I make a solution:
DECLARE #db_id AS int
DECLARE #db_name AS sysname
CREATE TABLE ##CompatibleDatabases
(
Name sysname,
CompanyName nvarchar(255),
ProductID smallint,
[Version] nvarchar(20),
[Code] int
)
SET ROWCOUNT 0
SELECT dbid AS [ID], Name AS [Name] INTO #AllDatabases FROM master..sysdatabases
SET ROWCOUNT 1
SELECT #db_id = [ID] FROM #AllDatabases
WHILE ##rowcount <> 0
BEGIN
SET ROWCOUNT 0
BEGIN TRY
SET #db_name = db_name(#db_id)
EXEC ('IF (
EXISTS ( SELECT * FROM [' + #db_name + '].INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME=''System'') AND
EXISTS ( SELECT * FROM [' + #db_name + '].INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME=''System'' AND COLUMN_NAME=''ProductID'' ) AND
EXISTS ( SELECT * FROM [' + #db_name + '].INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME=''System'' AND COLUMN_NAME=''Version'' )
)
BEGIN
DECLARE #insertStatement nvarchar(500)
IF (EXISTS ( SELECT * FROM [' + #db_name + '].INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME=''System'' AND COLUMN_NAME=''CompanyName'' ) )
SET #insertStatement=''INSERT INTO ##CompatibleDatabases SELECT ''''' + #db_name + ''''' AS Name, CompanyName, ProductID, [Version], [Code] FROM [' + #db_name + '].dbo.System''
ELSE
SET #insertStatement=''INSERT INTO ##CompatibleDatabases SELECT ''''' + #db_name + ''''' AS Name,''''' + #db_name + ''''' AS CompanyName, ProductID, [Version], NULL AS Code FROM [' + #db_name + '].dbo.System''
EXEC(#insertStatement)
END')
END TRY
BEGIN CATCH
END CATCH
DELETE #AllDatabases WHERE [ID] = #db_id
SET ROWCOUNT 1
SELECT #db_id = [ID] FROM #AllDatabases
END
SET ROWCOUNT 0
select * from ##CompatibleDatabases
DROP TABLE #AllDatabases
DROP TABLE ##CompatibleDatabases
I have a DB with 60 tables. In some of those tables I have a bit column named "Open" where I store a 0 if the record is not in use by an user (user access DB from a C# application) and an 1 if the record is in use.
Well, I need to get all the records from all the tables in my database where the "open" column value is true, or 1.
Is this even possible to do?
Here's a simple use of the undocumented sp_MSforeachtable:
EXEC sp_MSforeachtable
#command1='SELECT * FROM ? WHERE Open=1',
#whereand='AND o.id in (select object_id from sys.columns c where c.name=''Open'')'
Quick piece of code that gets list of tables within your database. Using a cursor loop through the answers checking it they have the fld named [open] and if it does the build a SQL statement and the execute this SQL string.
CREATE PROCEDURE usp_BulkTableOpenReport
AS
BEGIN
DECLARE #TBLS AS TABLE (REF INT IDENTITY (0,1), TABLENAME NVARCHAR(100), TABLEID BIGINT);
DECLARE #TBL AS NVARCHAR(100);
DECLARE #TBLID AS BIGINT;
DECLARE #SQL AS NVARCHAR(MAX);
DECLARE #I INT = 0;
DECLARE #M INT = 0;
DECLARE #V INT = 0
INSERT INTO #TBLS(TABLENAME,TABLEID)
SELECT NAME,OBJECT_ID FROM sys.tables
SELECT #M = MAX(REF) FROM #TBLS
WHILE #I <= #M
BEGIN
SELECT #TBL = TABLENAME, #TBLID= TABLEID FROM #TBLS WHERE REF = #I
/* CHECK TO MAKE INSURE THAT A FLD CALLED [OPEN] EXIST. */
SELECT #V = COUNT(*) FROM SYS.columns WHERE name = 'OPEN' AND OBJECT_ID = #TBLID
IF #V != 0
BEGIN
SET #SQL = 'SELECT * FROM [' + #TBL + '] WHERE [OPEN] = 1'
EXEC SP_EXECUTESQL #SQL
END;
SET #I = #I + 1
END;
END
GO
From your c# application exec the query "EXEC usp_BulkTableOpenReport" then loop through the table outputs.
I am using Silverlight and Linq-to-SQL to communicate with the database.
I have a stored procedure which receives 2 parameters (PFOID and Quantity) and Userid and returns a product name.
If we send multiple values like multiple pfoid's and quantity's it will return multiple product names shown as below
The stored procedure looks like this..
ALTER PROCEDURE [PFO].[PFOValidateUpdateData]
#PfoIDs xml, -- list of PFO ID's
#UserID uniqueidentifier --The Identity of the User making the call.
AS
BEGIN
-- SET DEFAULT BEHAVIOR
SET NOCOUNT ON -- Performance: stops rows affected messages
SET DEADLOCK_PRIORITY LOW -- This SP to be the Deadlock victim
-- Initialise Lock-Timeout and Deadlock vars for Insert
DECLARE #iLockTimeoutRetries as int
DECLARE #iDeadLockRetries as int
DECLARE #dtLockTimeoutSleepInterval as datetime
DECLARE #dtDeadlockSleepInterval as datetime
DECLARE #iErrorNumber as int
SET #iLockTimeoutRetries = 0
SET #iDeadLockRetries = 0
SET #dtLockTimeoutSleepInterval = sCommon.fnLockTimeoutSleepInterval()
SET #dtDeadlockSleepInterval= sCommon.fnDeadlockSleepInterval()
SET #iErrorNumber = 0
-- procedure specific
DECLARE #idoc as int
DECLARE #IsBrightstarUser as bit
RETRY:
BEGIN TRY
--Create Temp table to store stores!
CREATE TABLE [#PFOList]
(
[PFOId] nvarchar(50),
[Quantity] INT
)
--Create Temp table to store User stores!
CREATE TABLE [#UserStoreList]
(
[StoreID_XRef] nvarchar(50)
)
print CONVERT(varchar(1000), #PfoIDs)
--Create Document
EXEC sp_xml_preparedocument #idoc OUTPUT, #PfoIDs
-- Append to new list of Store records
INSERT INTO [#PFOList] (
[PFOId],
[Quantity]
)
SELECT [PFOID],[Quantity]
FROM OPENXML (#idoc, 'ArrayOfString/string',2)
WITH( [PFOID] nvarchar(50),[Quantity] [INT]) Stores
--WHERE [PFOId] Is Not NULL
-- Clean UP
exec sp_xml_removedocument #iDoc
-- are we dealing with a brightstar user?
SET #IsBrightstarUser = CASE WHEN exists
(SELECT *
FROM dbo.aspnet_UsersInRoles AS uir inner join
dbo.aspnet_Roles AS roles ON uir.RoleId = roles.roleid
WHERE roles.rolename = 'Brightstar Employee' and uir.userid = #userid)
THEN 1 ELSE 0 END
--Get User Storelist
INSERT INTO [#UserStoreList] (
[StoreID_XRef]
)
SELECT s.StoreId_XRef
FROM PFO.UserStoreLink us(nolock)
INNER JOIN PFO.Store s(nolock)
ON us.StoreId=s.StoreId
where UserId=#UserID
--Select * from [#PFOList]
--SELECT #IsBrightstarUser AS ISBrightstaruser
--SELECT * from [#UserStoreList]
--If BrightstarCustomer Update all the Quantities.
IF #IsBrightstarUser=1
BEGIN
UPDATE
PFO.PFO
SET
IsBrightstarReviewComplete = 1
,[ModifyingUsersID] = #UserID
,[ModifiedDate] = getdate()
,[PlannedQty] = pfol.[Quantity]
,[BrightstarReviewedQty]=pfol.[Quantity]
FROM
PFO.PFO as pfo
INNER JOIN [#UserStoreList] as stores on pfo.StoreId_XRef=stores.StoreID_XRef
INNER JOIN [#PFOList] as pfol on pfo.PFOId = pfol.PFOId
WHERE #IsBrightstarUser = 1
END
ELSE BEGIN
--Update Non Contrained Orders
UPDATE
PFO.PFO
SET
[ModifyingUsersID] = #UserID
,[ModifiedDate] = getdate()
,[PlannedQty] = pfol.[Quantity]
FROM
PFO.PFO (nolock) as pfo
INNER JOIN [#UserStoreList] as stores on pfo.StoreId_XRef=stores.StoreID_XRef
INNER JOIN [#PFOList] as pfol on pfo.PFOId = pfol.PFOId
WHERE pfo.IsBrightstarReviewComplete=1 AND IsConstraint=0
--SELECT * from PFO.PFO (nolock) where PFOId='04676723-2afb-49ff-9fa1-0131cabb407c'
--Update Contrained Orders
--Get Existing quantities for the User
CREATE TABLE #ExistingProductQuantity
(
[PfoID] nvarchar(100)
,[Product] nvarchar(255)
,[PlannedQty] INT
,[BrightstarReviewedQty] INT
)
CREATE TABLE #CustProductQuantity
(
[Product] nvarchar(255)
,[IsUpdatable] BIT
)
INSERT INTO #ExistingProductQuantity
( [PfoID],[Product],[PlannedQty],[BrightstarReviewedQty])
SELECT PFOId,InventoryId,PlannedQty,BrightstarReviewedQty
FROM PFO.PFO as pfo
INNER JOIN [#UserStoreList] as stores on pfo.StoreId_XRef=stores.StoreID_XRef
WHERE pfo.IsBrightstarReviewComplete=1 AND IsConstraint=1
UPDATE
#ExistingProductQuantity
SET [PlannedQty]=pfol.[Quantity]
FROM #ExistingProductQuantity eoq
INNER JOIN [#PFOList] as pfol on eoq.PFOId = pfol.PFOId
INSERT INTO #CustProductQuantity
( [Product],[IsUpdatable] )
SELECT
[Product],
CASE WHEN SUM(PlannedQty)<=SUM(BrightstarReviewedQty) THEN 1 ELSE 0 END
FROM #ExistingProductQuantity
GROUP BY [Product]
--SELECT * from #ExistingProductQuantity
--SELECT * from #CustProductQuantity
--Update the products that can be updatable
UPDATE
PFO.PFO
SET
[ModifyingUsersID] = #UserID
,[ModifiedDate] = getdate()
,[PlannedQty] = pfol.[Quantity]
FROM
PFO.PFO as pfo
INNER JOIN #UserStoreList as stores on pfo.StoreId_XRef=stores.StoreID_XRef
INNER JOIN #PFOList as pfol on pfo.PFOId = pfol.PFOId
INNER JOIN #CustProductQuantity as pr on pr.Product=pfo.InventoryId
WHERE pfo.IsBrightstarReviewComplete=1 AND pr.IsUpdatable=1 AND IsConstraint=1
--Return the products that are not updatabele
select [Product]
FROM #CustProductQuantity
where [IsUpdatable]=0
END
END TRY
BEGIN CATCH
-- Get the ErrorNumber
Set #iErrorNumber = ERROR_NUMBER()
--Handle Deadlock situation (Deletes, Inserts & Updates)
IF #iErrorNumber = 1205
BEGIN
-- If we have not made enough attempts to break the lock
IF #iDeadLockRetries < sCommon.fnMaxDeadlockRetries()
BEGIN
-- Increment the Attempt count
SET #iDeadLockRetries = #iDeadLockRetries + 1
-- Pause to allow the deadlock contention to clear
WAITFOR DELAY #dtDeadlockSleepInterval
GOTO RETRY
END
END
-- Handle Lock Timeout situation (Deletes, Inserts & Updates)
IF #iErrorNumber = 1222
BEGIN
-- If we have not made enough attempts to break the Deadlock
IF #iLockTimeoutRetries < sCommon.fnMaxLockTimeoutRetries()
BEGIN
-- Increment the Attempt count
SET #iLockTimeoutRetries = #iLockTimeoutRetries + 1
-- Pause to allow the lock contention to clear
WAITFOR DELAY #dtLockTimeoutSleepInterval
GOTO RETRY
END
END
exec Common.RethrowError
END CATCH
END
The result is as follows..
Product
6435LVWK-360-CD819E3
NSCHI535C1097I360-4C
NSCHU485C1819I360-0C
Return Value
0
My Linq-to-SQL connection is like this
[global::System.Data.Linq.Mapping.FunctionAttribute(Name="PFO.PFOValidateUpdateData")]
public int PFOValidateUpdateData([global::System.Data.Linq.Mapping.ParameterAttribute(Name = "PfoIDs", DbType = "Xml")] System.Xml.Linq.XElement pfoIDs, [global::System.Data.Linq.Mapping.ParameterAttribute(Name = "UserID", DbType = "UniqueIdentifier")] System.Nullable<System.Guid> userID)
{
IExecuteResult result = this.ExecuteMethodCall(this, ((MethodInfo)(MethodInfo.GetCurrentMethod())), pfoIDs, userID);
return ((int)(result.ReturnValue));
}
I am trying to retrieve all the data from the stored procedure but the when I debugging it the return value is "o"..
I would be grateful to you if you could help me retrieve all the data returned by the stored procedure... thank you very much...
If your stored procedure returns a collection of nvarchar's, then the signature of your Linq2Sql method is not correct. It should not return an int, but an ISingleResult.
So the correct signature will be:
public ISingleResult<string> PFOValidateUpdateData(...)
{
IExecuteResult result = this....;
return (ISingleResult<string>)result.ReturnValue;
}
var products = PFOValidateUpdateData(...).ToList();
If you want to return the results from multiple SELECT's in your stored procedure, you'll have to use IMultipleResults.
Well I know this is not the right way...for time being,its working for me...
I created an other table with two columns one ProductId and ID, I am inserting the values returned by the stored procedure,
in the designer.cs I am returning the table,
[global::System.Data.Linq.Mapping.FunctionAttribute(Name="PFO.PFOValidateUpdateData")]
public ISingleResult<PFOValidData> PFOValidateUpdateData([global::System.Data.Linq.Mapping.ParameterAttribute(Name = "PfoIDs", DbType = "Xml")] System.Xml.Linq.XElement pfoIDs, [global::System.Data.Linq.Mapping.ParameterAttribute(Name = "UserID", DbType = "UniqueIdentifier")] System.Nullable<System.Guid> userID)
{
IExecuteResult result = this.ExecuteMethodCall(this, ((MethodInfo)(MethodInfo.GetCurrentMethod())), pfoIDs, userID);
return ((ISingleResult<PFOValidData>)(result.ReturnValue));
}
And in the Domainservice
List<string> PFOValidateUpdateData(string pfoIds, Guid userID)
{
List<string> productIdList = new List<string>();
// Acquire the int
result = this.DataContext.PFOValidateUpdateData(element, userID);
foreach (var item in result)
{
productIdList.Add(item.ProductID);
}
return productIdList;
To get the multiple values returned by the stored procedure....
Please let me know if there is a better way to solve this... thank you