Best way to insert values multiple times from data layer to stored procedure? - asp.net

Hi
I have DAL Layer, from where invoking a stored procedure to insert values into the table.
E.g.:-
CREATE PROCEDURE [dbo].[DataInsert]
#DataName nvarchar(64)
AS
BEGIN
INSERT INTO
table01 (dataname)
VALUES
(#dataname)
END
Now as requirement changed, per client request i have to add values 5 times. So what is the best practice?
Do i call this Stored Procedure 5 times from my DAL?
or
Pass all the values (may be comma separated) to storedprocedure in one go and then let the stored procedure add it for 5 times?
BTW. Its not always 5 times. It is changeable.

You could create a user-defined table type;
CREATE TYPE [dbo].[SomeInfo] AS TABLE(
[Id] [int] NOT NULL,
[SomeValue] [int] NOT NULL )
Define your stored proc as such;
CREATE PROCEDURE [dbo].[AddSomeStuff]
#theStuff [SomeInfo] READONLY
AS
BEGIN
INSERT INTO SOMETABLE ([...columns...])
SELECT [...columns...] from #theStuff
END
Then you'll need to create a datatable (called table below) that matches the schema and call the stored proc as so;
var cmd = new SqlCommand("AddSomeStuff", sqlConn) {CommandType = CommandType.StoredProcedure};
var param = new SqlParameter("#theStuff", SqlDbType.Structured) {Value = table};
cmd.Parameters.Add(param);
cmd.ExecuteNonQuery();

btw this proc works - I've just written and tested it see results below!
CREATE PROCEDURE [dbo].[DataInsert]
#DataName nvarchar(max) AS
BEGIN
DECLARE #pos SMALLINT, #str VARCHAR(max)
WHILE #DataName <> ''
BEGIN
SET #pos = CHARINDEX(',', #DataName)
IF #pos>0
BEGIN
SET #str = LEFT(#DataName, #pos-1)
SET #DataName = RIGHT(#DataName, LEN(#DataName)-#pos)
END
ELSE
BEGIN
SET #str = #DataName
SET #DataName = ''
END
INSERT INTO table01 VALUES(CONVERT(VARCHAR(100),#str))
END
END
GO
then run it: -
EXEC #return_value = [dbo].[DataInsert]
#DataName = N'five, bits, of, your, data'
*rows from table01: *
five
bits
of
your
data
(5 row(s) affected)

I'd either call your proc repeatedly(that would be my choice), or else you could use XML to pass in a list of values as a single parameter.
http://support.microsoft.com/kb/555266

Instead of fancy SQL code that is difficult to maintain and is not scalable, I would simply go to invoking your stored procedure multiple times.
If performance or transactional behavior is an issue, you can consider to send the commands in a single batch.
You talked about 5 insert. If the number of record to insert is much greater, you could consider bulk insert as well.

Related

Return value to textbox from stored procedure

Having trouble returning the value ID value I need for output back to the textbox in the form. Webforms and ADO.net
I tried adding a param identity as an int and OUT clause, while setting identity = scope_identity and returning the value then using the pattern my team is currently using for ExecuteNonQuery with anonymous parameter classes passing in values and tried passing the #identity value to the textbox.text for the id.
DataManager.Db.ExecuteNonQuery("DefaultConnection", "usp_CreateNewSalesTerritory",
new SqlParameter("#orgId", orgId),
new SqlParameter("#identity", salesTerritoryIdTextBox.Text),
new SqlParameter("#salesTerritoryName", salesTerritories.Name),
new SqlParameter("#createdBy", salesTerritories.CreatedBy),
new SqlParameter("#createdDate", salesTerritories.CreatedDate),
new SqlParameter("#updatedBy", salesTerritories.UpdatedBy),
new SqlParameter("#updatedDate", salesTerritories.UpdatedDate),
new SqlParameter("#isActive", salesTerritories.IsActive));
CREATE PROCEDURE dbo.usp_CreateNewSalesTerritory
#orgId VARCHAR(255),
#salesTerritoryName VARCHAR(255),
#createdBy VARCHAR(255),
#createdDate DATETIME,
#updatedBy VARCHAR(255),
#updatedDate DATETIME,
#isActive BIT,
#identity INT OUTPUT
AS
BEGIN
SET NOCOUNT ON;
INSERT INTO SalesTerritory (OrganizationId, Name, IsActive,
CreatedBy, CreatedDate, UpdatedBy, UpdatedDate)
VALUES (#orgId, #salesTerritoryName, #isActive,
#createdBy, #createdDate, #updatedBy, #updatedDate);
--SELECT SCOPE_IDENTITY();
--RETURN SCOPE_IDENTITY();
--SELECT ##IDENTITY;
SET #identity = SCOPE_IDENTITY()
END;
RETURN #identity
I expected to get the new inserted ID value for that record, instead, I get the default value of 0 on the screen
Normally, you would call such a stored procedure in "pure" ADO.NET using the .ExecuteNonQuery() method on the SqlCommand object - since it's an INSERT statement.
But now, your stored procedure is actually returning some data - so you really need to treat this like a "normal" SELECT stored procedure.
Assuming you're always returning just the SCOPE_IDENTITY() value - preferably like this:
SELECT SCOPE_IDENTITY();
which is just one single value - you can use the .ExecuteScalar() method on the SqlCommand object - something like this:
object returned = sqlCmd.ExecuteScalar();
if (returned != null)
{
int newIdValue = Convert.ToInt32(returned);
}
// else -> nothing was returned, so most likely no row has been inserted -> handle it appropriately
So maybe you already have a "wrapper" method for .ExecuteScalar() on your DataManager.Db object - or maybe you need to add it. Give it a try - I'm pretty sure this will solve the issue.
I would avoid using the RETURN ... statement - SQL Server stored procedure by default will always return the number of rows that were affected by your stored procedure - don't change that "standard" behavior, if you can.

Entity Framework shows error when called stored procedure

In my project EF calls a stored procedure which is shown below. It returns either 1 or scope identity.
On EF function imports, the stored procedure is listed with a return type of decimal.
When the stored procedure returns scope identity, everything is ok.
But when if condition of sp satisfies, ef throws error as
The data reader returned by the store data provider does not have enough columns for the query requested.
Pls help..
This is my stored procedure:
#VendorId int,
#ueeareaCode varchar(3),
#TuPrfxNo varchar(3),
#jeeSfxNo varchar(4),
#Tjode varchar(3),
#uxNo varchar(3),
#TyufxNo varchar(4),
#Iyuy bit
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
SET NOCOUNT ON;
IF EXISTS (Select dfen_id
from dbo.efe_phfedwn_eflwn
where
[yu] = #Tyuode and
[uy] = #TuyxNo and
[yuno] = #Tuo)
return 1
ELSE
Begin
INSERT INTO dbo.yu
....................
Select Scope_Identity()
End
END
The error tells us that EF is expecting a result set and when we use RETURN we don't get a result set. Your error means that the stored procedure is returning an integer but EF is expecting a decimal, so we just CAST the selected values to a decimal.
So modify the SQL so that we SELECT instead of RETURN, like so (not forgetting to use CAST):
IF EXISTS (Select cntct_ctr_phn_ln_id
from dbo.cntct_ctr_phn_ln
where
[toll_free_phn_area_cd] = #TollfreeareaCode and
[toll_free_phn_prfx_no] = #TollfreePrfxNo and
[toll_free_phn_sfx_no] = #TollfreeSfxNo)
SELECT CAST(1 AS decimal)
Then also CAST the result of SCOPE_IDENTITY() to a decimal:
SELECT CAST(SCOPE_IDENTITY() AS decimal)

Stored procedure passing parameter MAX size Limite

I'm Using Microsoft SQL server 2005
I Created stored procedure for generate the report.
ASP.NET from is used for passing parameter for the stored procedure.
Problem is it's not taking All the PartNumber what selected for parameter. It's taking ONLY 225 PartNumber and generate report for only those partNumber but in real I have more than 700 PartNumber.
IS there any other way where I can extend the size for parameter.?
Is there more size limit in sql server 2008.?
Is there any way to store this "#sqlQuery nvarchar(4000)" variable to XML variable.?
4000 is the max Size for nvarchar (because I tried to extend it and it's not accept more than 4000). Xml variable has no limit.
Example for Parameter values (Passed From ASP.NET )
PartNumber
314013
314039
314047
314054
314062
314070
314088
314096
314104
314344
314351
314377
314393
Stored procedure
USE [Reportbox]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[spCreateReport2]
(#prod nvarchar(4000))
AS
BEGIN
DECLARE #sqlQuery nvarchar(4000)
declare #intMonth nvarchar(2)
declare #intMonth1 nvarchar(2)
declare #intMonth2 nvarchar(2)
declare #intMonth3 nvarchar(2)
declare #intMonth4 nvarchar(2)
declare #intMonth5 nvarchar(2)
SELECT #intMonth = fiscalmonth FROM FiscalWeeks WHERE CAST(FLOOR(CAST(GETDATE() AS FLOAT)) AS DATETIME) between weekstart and weekend
if #intmonth-1<=0 BEGIN set #intmonth1=#intmonth-1+12 END else set #intMonth1=#intMonth-1
if #intmonth-2<=0 BEGIN set #intmonth2=#intmonth-2+12 END else set #intmonth2=#intmonth-2
if #intmonth-3<=0 BEGIN set #intmonth3=#intmonth-3+12 END else set #intmonth3=#intmonth-3
if #intmonth-4<=0 BEGIN set #intmonth4=#intmonth-4+12 END else set #intmonth4=#intmonth-4
if #intmonth-5<=0 BEGIN set #intmonth5=#intmonth-5+12 END else set #intmonth5=#intmonth-5
Set #sqlQuery =
'select distinct d.PROD80, DESC80, SUM_AVGU80, AVGU80, SUM_ONHA80, d.ONHA80, SUM_SAFE80, d.SAFE80,
MAX_FOQT80, MAX_ABCC80, MAX_MINQ80,
SUM_WEEK_NO_PO, SUM_TRIG80, d.TRIG80, SUM_BQTY80, DQTY80, OQTY80,
CASE WHEN d.AVGU80<>0 THEN CAST(ROUND(d.ONHA80/d.AVGU80,0) AS INT) ELSE 0 END AS WKS30
FROM DI80ACT00 d INNER JOIN vwDataAtCompanyLevel v on (d.prod80=v.prod80)
LEFT OUTER JOIN DI80ACT01 t on (d.prod80=t.prod80) and t.ware80 <> ''30''
WHERE d.prod80 in (' + #prod + ') and d.prod80<>''HLW54B'' and d.ware80=''30''
GROUP BY d.PROD80, DESC80, SUM_AVGU80, AVGU80, SUM_ONHA80, d.ONHA80, SUM_SAFE80, d.SAFE80,
MAX_FOQT80, MAX_ABCC80, MAX_MINQ80,SUM_HSTA80,SUM_HSTB80,SUM_HSTC80,SUM_HSTD80,SUM_HSTE80,SUM_HSTF80,SUM_POOR80,POOR80,SUM_TWIN80,SUM_WEEK_No_PO,SUM_TRIG80,TRIG80,SUM_BQTY80,DQTY80,OQTY80'
exec(#sqlQuery)
END
Any Help Or details will be very helpful
Thank you
Use NVARCHAR(MAX) which supports over 1 billion characters. However I don't really expect your IN() query against 700 values to perform very well at all.
If they choose ALL then pass the string 'ALL' to the parameter, and only include the IN() list when they haven't selected ALL. So in the SQL:
Set #sqlQuery = 'select distinct
...
WHERE d.prod80<>''HLW54B'' and d.ware80=''30'''
+ CASE WHEN #prod = 'ALL' THEN '' ELSE
'AND d.prod80 in (' + #prod + ')' END
+ 'GROUP BY ...'
There is no reason to have a massive IN() clause that lists every single value in the table.

How to generate a column with id which increments on every insert

This is my table where i want my PNRNo to be generated as 'PNRRES001' for the first entry, and consecutive entries with 'PNRRES002','PNRRES002' so on.
So while creating table only i called that column to function which will generate the PNR no, User just has to enter the CustomerNo from the front end, and data wit PNR & Customer No will updated to the PNRDetails table.
CREATE TABLE PNRDetails(PNRNo AS (DBO.FuncIncPNR()) ,customerNo INT
--FUNCTION TO GENERATE THE PNR NUMBER
ALTER FUNCTION dbo.FuncIncPNR()
RETURNS VARCHAR(20)
AS
BEGIN
DECLARE #RR VARCHAR(20) SET #RR='PNRRESA001'
--here i have checked if no value is there then return the first value as 'PNRRESA001'
IF((SELECT COUNT(*)FROM PNRDetails)=0)
BEGIN
RETURN #RR
END
ELSE
-- if any value is there then take the last value and add 1 to it and update to the table
BEGIN
DECLARE #pnr VARCHAR(20),#S1 VARCHAR(20),#S2 INT
DECLARE PNRCursor CURSOR Static
FOR SELECT PNRNo FROM PNRDetails
OPEN PNRCursor
FETCH LAST FROM PNRNo INTO #pnr
SET #S1=SUBSTRING(#pnr,1,7)
SET #S2=RIGHT(#PNR,3)
SET #S2=#S2+1;
SET #pnr=#S1+#S2;
END
RETURN #pnr
END
--Here am inserting only customerNo as 5 and the PNR should be generated by my function
INSERT INTO PNRDetails VALUES(5)
--it shows 1 row updated :)
SELECT * FROM PNRDetails
-- but when i run select command it shows
--Maximum stored procedure, function, trigger, or view nesting level exceeded (limit 32). :(
U can run this.And pls do help if u find anything that could help me. any help will be appreciated...
Waiting for your kind response...
You could try to use a computed column and an identity column instead.
create table PNRDetails
(
ID int identity,
PNRNo as 'PNRRES'+right(1000+ID, 3),
customerNo int
)
I would suggest just using an IDENTITY instead as your id, let SQL Server handle the assignment of each id number with all it's built-in guards for concurrency, and leave the formatting up to the UI....or, create a computed column that defines the formatted version of the ID if you really do need it in the DB.
The risk you run with your intended approach is:
poor performance
concurrency issues - if loats of ids are being generate around the same time
If you are happy to change the table structure. Following will do the job.
CREATE TABLE [dbo].[PNRDetails](
[autoId] [int] IDENTITY(1,1) NOT NULL,
[prnNo] AS ('PNRRES'+right('000'+CONVERT([varchar](3),[dbo].[GetRowCount]([autoId]),(0)),(3))),
[customerNo] [int] NOT NULL,
CONSTRAINT [PK_Table1] PRIMARY KEY CLUSTERED
(
[autoId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
EDIT: to address identity issue for your requirement pls create following function and pass the [autoId] in as above (edited) in the computed column.
CREATE FUNCTION dbo.GetRowCount
(
#autoId INT
)
RETURNS INT
AS
BEGIN
DECLARE #RESULTS AS INT
SELECT #RESULTS = COUNT(autoId) FROM PNRDetails WHERE PNRDetails.autoId<#autoId
RETURN #RESULTS + 1
END
GO
--INSERT
INSERT INTO PNRDetails (customerNo) VALUES(5)
1) You can use an identity column in your database (INTEGER)
PROS: easy/No gaps in between generated ids
CONS: You have to select the inserted id & return via procedure/query
if you were to show it to end user
2) Define a database sequence
PROS: easy to implement/Can be stored/shown to user before the form is
even saved
CONS: Gaps in between if the certain id is once generated & not used
3). Select max(id) from column + 1
PROS: Useful where only single user inserts in a table
CONS: disastrous if you were in an environment where multiple users
were inserting in the same tablle (mismatched max ids)
4) Use a database trigger to autoincrement the column
PROS:automated
CONS: hard to debug (you have to make sure it don't breaks for some
reason otherwise insert fails)
Change the way your trigger works. Something like this
CREATE FUNCTION dbo.fn_FuncIncPNR(#ID int)
RETURNS varchar(20)
BEGIN
Declare #Retval varchar(20),
#No varchar(4)
Select #No = convert(varchar(4), #ID)
while Len(#No) < 4
Select #No = '0' + #No
Select #Retval = 'PNRRESA' + #No
RETURN #Retval
END
You will notice there is a parameter field
Change your table create to this
CREATE TABLE PNRDetails(PNRNo AS (dbo.fn_ShowPNRNo(wID)), wID int IDENTITY(1,1) NOT NULL, customerNo INT)
That should solve your problem

Ordering SQL Server results by IN clause

I have a stored procedure which uses the IN clause. In my ASP.NET application, I have a multiline textbox that supplies values to the stored procedure. I want to be able to order by the values as they were entered in the textbox. I found out how to do this easily in mySQL (using FIELD function), but not a SQL Server equivalent.
So my query looks like:
Select * from myTable where item in #item
So I would be passing in values from my application like '113113','112112','114114' (in an arbitrary order). I want to order the results by that list.
Would a CASE statement be feasible? I wouldn't know how many items are coming in the textbox data.
How are you parameterising the IN clause?
As you are on SQL Server 2008 I would pass in a Table Valued Parameter with two columns item and sort_order and join on that instead. Then you can just add an ORDER BY sort_order onto the end.
From KM's comment above...
I know you didn't state it is comma seperated, but if it was a CSV or even if you have it space seperated you could do the following.
DECLARE #SomeTest varchar(100) --used to hold your values
SET #SomeTest = (SELECT '68,72,103') --just some test data
SELECT
LoginID --change to your column names
FROM
Login --change to your source table name
INNER JOIN
( SELECT
*
FROM fn_IntegerInList(#SomeTest)
) n
ON
n.InListID = Login.LoginID
ORDER BY
n.SortOrder
And then create fn_IntegerInList():
CREATE FUNCTION [dbo].[fn_IntegerInList] (#InListString ntext)
RETURNS #tblINList TABLE (InListID int, SortOrder int)
AS
BEGIN
declare #length int
declare #startpos int
declare #ctr int
declare #val nvarchar(50)
declare #subs nvarchar(50)
declare #sort int
set #sort=1
set #startpos = 1
set #ctr = 1
select #length = datalength(#InListString)
while (#ctr <= #length)
begin
select #val = substring(#InListString,#ctr,1)
if #val = N','
begin
select #subs = substring(#InListString,#startpos,#ctr-#startpos)
insert into #tblINList values (#subs, #sort)
set #startpos = #ctr+1
end
if #ctr = #length
begin
select #subs = substring(#InListString,#startpos,#ctr-#startpos)
insert into #tblINList values (#subs, #sort)
end
set #ctr = #ctr +1
set #sort = #sort + 1
end
RETURN
END
This way your function creates a table that holds a sort order namely, SortOrder and the ID or number you are passing in. You can of course modify this so that you are looking for space rather then , values. Otherwise Martin has the right idea in his answer. Please note in my example I am using one of my tables, so you will need to change the name Login to whatever you are dealing with.
the same way you concatenate ('113113','112112','114114') to pass to the sql sentence in the where clausule you can concatenate
order by
case item
when '113113' then 1
when '112112' then 2
when '114114' then 3
end
to pass to your order by clausule

Resources