SQL retrieving OUTPUT into a asp.net form - asp.net

I have a SQL stored procedure that OUTPUTs the number to a row after I insert of few records. The query works great and returns what I need, although. I would like to take the output from the query and read it into a label. Can someone shine a little light? Thanks.
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("#spName", txt_Name.Text));
cmd.Parameters.Add(new SqlParameter("#spSource", txt_Source.Text));
cmd.Parameters.Add(new SqlParameter("#spDateCreated", txt_DateCreated.Text));
paramReturnNumber = cmd.Parameters.AddWithValue("#out", SqlDbType.NVarChar);
paramReturnNumber.Direction = ParameterDirection.Output;
cmd.ExecuteNonQuery();
The Query:
ALTER PROCEDURE [dbo].[usps_InsertIntoMedia]
#spName varchar(100),
#spSource varchar(100),
#spDateCreated datetime
AS
SET NOCOUNT ON;
DECLARE #out nvarchar
BEGIN
INSERT INTO Media (Name, Source, DateCreated)
OUTPUT inserted.Number
VALUES(#spName,#spSource,#spDateCreated )
Select #out = Media.Number
FROM Media
END

I am using the following technique:
Hashtable ht = new Hashtable();
foreach (SqlParameter sqlp in cmd.Parameters)
{
if ((sqlp.Direction == ParameterDirection.InputOutput) ||
(sqlp.Direction == ParameterDirection.Output))
{
ht.Add(sqlp.ParameterName, sqlp.Value);
}
}
<lblName>.Text = (string)ht["#out"];

The solution to this problem was to specify the OUTPUT parameter using the SET statment.

Related

How to store more than 8000 characters and assign large concatenated string in SQL Server 2008?

I am trying to concatenate the large number of id'd and to update the status of all id's.
For example:
aclid in (4604019,4604018,4604017,4604016,4604015,4604014,4604013,4604012,4604011,4604010,4604009,4604008,4604007,4604006,4604005,4604004,4604003,4604002,4604001,4604000,4603999,4603998,4603997,4603996,4603995,4603994,4603993,4603992,4603991,4603990,4603989,4603988)`
Please check my stored procedure:
ALTER PROCEDURE [dbo].[VT_ACLReportChangeStatus]
(#ChangeStatus nvarchar(50) = null,
#ACLId nvarchar(max))
AS
/* Exec VT_ACLReportChangeStatus 'Complete','4599473,4599472,4599471,4599469,4599468' */
BEGIN
UPDATE VT_ACLReport
SET Status = #ChangeStatus
WHERE ACLId IN (SELECT * FROM SplitDelimiterString(#ACLId,','))
END
Please check my code behind:
ACLId = ACLId.ToString().Trim(',');
using (SqlConnection con = new SqlConnection(cs))
{
cmd = new SqlCommand("VT_ACLReportChangeStatus", con);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.CommandTimeout = 3600;
cmd.Parameters.Add(new SqlParameter("#ACLId", SqlDbType.NVarChar,-1));
cmd.Parameters.Add(new SqlParameter("#ChangeStatus", SqlDbType.NVarChar, 50));
cmd.Parameters["#ACLId"].Value = ACLId;
cmd.Parameters["#ChangeStatus"].Value = ddlChangeStatus.SelectedItem.Text.ToString();
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
AclId column data type is bigint identity.
Please can you help me in concatenating large string and to update all rows whose aclid is present.
I would suggest, create one user defined table type in sql and one class in sourecode with your respective data. You can pass object of this class to sql and in your SP you can use join between main table and this table(which is received as input parameter) to update data.
Thanks all of you for your answers.. Actually it was silly mistake,while calling splitting function in Stored procedure. In function it was varchar(8000). :) solved it.
ALTER FUNCTION [dbo].[SplitDelimiterString] (#StringWithDelimiter VARCHAR(max), #Delimiter VARCHAR(max))
RETURNS #ItemTable TABLE (Item VARCHAR(max))
AS
BEGIN
DECLARE #StartingPosition INT;
DECLARE #ItemInString VARCHAR(max);
SELECT #StartingPosition = 1;
--Return if string is null or empty
IF LEN(#StringWithDelimiter) = 0 OR #StringWithDelimiter IS NULL RETURN;
WHILE #StartingPosition > 0
BEGIN
--Get starting index of delimiter .. If string
--doesn't contain any delimiter than it will returl 0
SET #StartingPosition = CHARINDEX(#Delimiter,#StringWithDelimiter);
--Get item from string
IF #StartingPosition > 0
SET #ItemInString = SUBSTRING(#StringWithDelimiter,0,#StartingPosition)
ELSE
SET #ItemInString = #StringWithDelimiter;
--If item isn't empty than add to return table
IF( LEN(#ItemInString) > 0)
INSERT INTO #ItemTable(Item) VALUES (#ItemInString);
--Remove inserted item from string
SET #StringWithDelimiter = SUBSTRING(#StringWithDelimiter,#StartingPosition +
LEN(#Delimiter),LEN(#StringWithDelimiter) - #StartingPosition)
--Break loop if string is empty
IF LEN(#StringWithDelimiter) = 0 BREAK;
END
RETURN
END

How to use Oracle Complex Type out parameter in .NET

I have an Oracle procedure that passes a complex type as an out parameter that I need to be able to use within .NET. I have not had much luck finding a good example of how to make something like this work so I am hoping some here might have the answer or have done this.
Oracle.manageddataAccess.dll version# 4.121.1.0
Code:
CREATE OR REPLACE TYPE APPS.gary_pol_tbl_type AS TABLE OF gary_pol_rec_type;
CREATE OR REPLACE PROCEDURE APPS.gary_pol_test3 ( x_gary_pol IN OUT apps.gary_pol_tbl_type ) AS
CURSOR c1 IS
SELECT org_id,
po_type,
po_header_id,
po_num,
po_release_id,
po_release_num,
vendor_id,
vendor_name,
vendor_site_num,
vendor_site_name,
pay_site_id,
currency_code,
po_amount,
po_date,
buyer_name,
shipment_num,
po_line_id,
line_num,
po_creation_date,
release_date,
item_num,
item_description,
uom,
po_qty,
received_qty,
unit_price,
taxable_flag,
closed_date,
entity,
branch,
planner_name,
attribute1,
attribute2,
batch_number,
processed_flag,
wm_uuid,
creation_date,
created_by,
last_update_date,
last_updated_by
FROM xxit.xxfin_ap_imagenow_pol_out
WHERE ROWNUM < 2001
ORDER BY org_id ASC NULLS LAST,
po_header_id ASC NULLS LAST,
po_release_id ASC NULLS LAST,
shipment_num ASC NULLS LAST,
po_line_id ASC NULLS LAST,
line_num ASC NULLS LAST;
BEGIN
FOR c1_rec IN c1 LOOP
x_gary_pol.EXTEND;
x_gary_pol ( x_gary_pol.LAST ) :=
apps.gary_pol_rec_type ( c1_rec.org_id,
c1_rec.po_type,
c1_rec.po_header_id,
c1_rec.po_num,
c1_rec.po_release_id,
c1_rec.po_release_num,
c1_rec.vendor_id,
c1_rec.vendor_name,
c1_rec.vendor_site_num,
c1_rec.vendor_site_name,
c1_rec.pay_site_id,
c1_rec.currency_code,
c1_rec.po_amount,
c1_rec.po_date,
c1_rec.buyer_name,
c1_rec.shipment_num,
c1_rec.po_line_id,
c1_rec.line_num,
c1_rec.po_creation_date,
c1_rec.release_date,
c1_rec.item_num,
c1_rec.item_description,
c1_rec.uom,
c1_rec.po_qty,
c1_rec.received_qty,
c1_rec.unit_price,
c1_rec.taxable_flag,
c1_rec.closed_date,
c1_rec.entity,
c1_rec.branch,
c1_rec.planner_name,
c1_rec.attribute1,
c1_rec.attribute2,
c1_rec.batch_number,
c1_rec.processed_flag,
c1_rec.wm_uuid,
c1_rec.creation_date,
c1_rec.created_by,
c1_rec.last_update_date,
c1_rec.last_updated_by );
END LOOP;
apps.gary_pol_tbl_type ) );
END gary_pol_test3;
I have seen some references in the searching i have done by setting the oracleDBType.... to an object or array but i don't have those options. I could see where the object might be what I am looking for.
Here is my code in c# that is trying to read this.
public static DataTable test2()
{
DataTable dt = new DataTable();
try
{
using (OracleConnection cn = BSIC_DAL.OracleHelpers.createOracleConnection())
{
OracleDataAdapter da = new OracleDataAdapter();
OracleCommand cmd = new OracleCommand();
cmd.Connection = cn;
cmd.CommandText = "apps.gary_pol_test3";
cmd.CommandType = CommandType.StoredProcedure;
//cmd.Parameters.Add("p_batch_number", OracleDbType.Int16).Value = 133;
cmd.Parameters.Add("x_gary_pol", OracleDbType.RefCursor).Direction = ParameterDirection.Output;
da.SelectCommand = cmd;
da.Fill(dt);
return dt;
}
}
catch (Exception ex)
{
return null;
throw ex;
}
}
how do i consume an oracle complex type like the above in .Net?
Thanks for the help
Why don't you simply return a RefCursor?
Should be like this:
CREATE OR REPLACE PROCEDURE APPS.gary_pol_test3 ( x_gary_pol OUT SYS_REFCORSOR) AS
begin
open x_gary_pol for
SELECT org_id, po_type, po_header_id, ...
FROM xxit.xxfin_ap_imagenow_pol_out
WHERE ROWNUM < 2001
ORDER BY org_id ASC NULLS LAST, ...
end;
In C# it should be like this one (not verified):
cmd.Parameters.Add("x_gary_pol", OracleDbType.RefCursor).Direction = ParameterDirection.Output;
da.SelectCommand = cmd;
cmd.ExecuteNonQuery();
da.Fill(dt);

Inserting into sql database using the function

I am new in programming, especially in using sql server . I have a User page with text boxes and submit button. When a user enters information to text boxes and press the button, the information is added to database. There is a column UserID in the database which should be created after all information is added to the database.UserID should be consist of UserLastName and AutoIncrementNumber(column of the database which automatically is assigned to a new row) I have a function for this UserID column and i don't know how to make everything work. Please help me.
Thank you!
Here is code:
using (SqlConnection conn = new SqlConnection(#"Data Source=MyDataBase;Initial Catalog=MyDataBase;Integrated Security=True;"))
SqlCommand CmdSql = new SqlCommand
("INSERT INTO [tbluser] ([UserID],[UserLastName], [UserFirstName], [UserMiddleInitial] SELECT [dbo].[usernamehandle](#UserFirstName),#UserLastName, #UserFirstName, #UserMiddleInitial", conn);
conn.Open();
CmdSql.Parameters.AddWithValue("#UserLastName", txtNewUserLN.Text.ToString());
CmdSql.Parameters.AddWithValue("#UserFirstName", txtNewUserFN.Text.ToString());
CmdSql.Parameters.AddWithValue("#UserMiddleInitial", txtNewUserMI.Text.ToString());
CmdSql.Connection = conn;
CmdSql.ExecuteNonQuery();
conn.Close();
And here is function:
USE [MyDataBase]
GO
/****** Object: UserDefinedFunction [dbo].[usernamehandle] Script Date: 04/07/2013 17:25:23 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER FUNCTION [dbo].[usernamehandle]
(#newuserName nchar(10))returns nchar(10)
AS
BEGIN
DECLARE #s2 nchar(256)
SET #s2 = ''
DECLARE #p int
DECLARE #ULN char(256)
DECLARE #UNAI int
SELECT #ULN = UserLastName FROM tblUser
SELECT #UNAI = UserNameAutoIncre FROM tbluser
SET #s2 = #UNAI
while #p <=6 begin
DECLARE #c int
SET #c = ascii(substring(#newUserName, #p, 1))
SET #s2 += char(#c)
end
return #s2
end
Try to call directly your function in SQL:
Notes: please check the parameter for the function. I am assuming the parameter is user's first name.
SqlCommand CmdSql = new SqlCommand
("INSERT INTO [tbluser] ([UserID],[UserLastName], [UserFirstName], [UserMiddleInitial]) SELECT [dbo].[usernamehandle](#UserFirstName), #UserLastName, #UserFirstName, #UserMiddleInitial, conn);
You can't use function to insert data, function only used for select statement means only for DDL not for DML, for that you have to use Stored Procedure.

Stored Procedure Return Unique Identifier

I have a question which has been frustrating me and I have googled and googled and can't find what I want.
I have this SQL Server stored procedure, which works great and returns the unique identifier:
ALTER PROCEDURE [dbo].[mcd_AddLogin]
#UserName nvarchar(256),
#Password nvarchar(256),
#UID uniqueidentifier OUTPUT
AS
BEGIN
IF( #UID IS NULL )
SELECT #UID = NEWID()
ELSE
BEGIN
IF( EXISTS( SELECT [USERNAME] FROM dbo.LoginPassing_Active) )
RETURN -1
END
Declare #Active bit
Declare #Exp_Date datetime
Set #Active = 1
Set #Exp_Date = DATEADD(mi, 1, GETDATE())
INSERT dbo.LoginPassing ([USERNAME], [PASSWORD], [ACTIVE], [EXP_DATE], [UID])
VALUES (#UserName, #Password, #Active, #Exp_Date, #Uid)
RETURN 0
END
I am trying to use this in and ASP.NET application, and am getting the following error:
Procedure or function 'mcd_AddLogin' expects parameter '#UID', which was not supplied.
Below is the code in my ASP.Net application, can anyone help me solve what is going wrong, I'm sure its really simple and I have just missed a trick:
Dim conSQL As New SqlConnection
conSQL.ConnectionString = My.Settings.conSQL
conSQL.Open()
Dim comSQL As New SqlCommand
comSQL.Connection = conSQL
comSQL.CommandText = "mcd_AddLogin"
comSQL.CommandType = CommandType.StoredProcedure
comSQL.Parameters.Add("#Username", SqlDbType.NVarChar).Value = "username"
comSQL.Parameters.Add("#Password", SqlDbType.NVarChar).Value = "password"
comSQL.ExecuteNonQuery()
litAD.Text = comSQL.Parameters("#UID").Value
Appreciate your help in advance.
Thanks,
Steve
In stored procedure you have output parameter, then you must provide that parameter and after SP execution you can get output value from parameter.
Try this:
comSQL.Parameters.Add("#Password", SqlDbType.NVarChar).Value = "password"
comSQL.Parameters.Add("#UID", SqlDbType.Int)
comSQL.Parameters("#UID").Direction = ParameterDirection.Output
comSQL.ExecuteNonQuery()
litAD.Text = comSQL.Parameters("#UID").Value
You need to spacefiy the Parameter Direction and pass it before calling ExecuteNonQuery()
eg
myParm.Direction = ParameterDirection.Output
Please read more about Input and Output Parameters
Turns out I was googling the wrong thing - I wanted OUTPUT parameters, I solved the problem with my code below:
comSQL.Connection = conSQL
comSQL.CommandText = "mcd_AddLogin"
comSQL.CommandType = CommandType.StoredProcedure
comSQL.Parameters.Add("#Username", SqlDbType.NVarChar).Value = "spearce"
comSQL.Parameters.Add("#Password", SqlDbType.NVarChar).Value = "kintikai"
comSQL.Parameters.Add("#UID", SqlDbType.UniqueIdentifier)
comSQL.Parameters("#UID").Direction = ParameterDirection.Output
comSQL.ExecuteNonQuery()
litAD.Text = comSQL.Parameters("#UID").Value
Thanks for your help anyways.

how to use parameter and stored procedure

All what i am trying to do here is to set the Status field to "Complete" using stored procedure but for some reason it is not updating my table after i run the stored procedure. can someone please help me here and tell what am i doing wrong? thanks
//here is the stored proc
CREATE PROCEDURE sp_Update
#ID varchar
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
if exists (select Post_ID from MyTable WHERE Post_ID = #ID)
BEGIN
UPDATE MyTable
SET Status = 'Complete'
WHERE Post_ID = #ID
END
END
//and here is the code behind
foreach (GridViewRow gr in GV_Action.Rows)
{
//string strID = gr.Cells[1].Text;
string ID = gr.Cells[1].Text;
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString);
SqlCommand cmd = new SqlCommand("sp_Update", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#ID", SqlDbType.VarChar).Value = ID;
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
In the code "gr.Cells[1].Text" Cells[x] is zero based. If the ID is in the very first column then you need 'gr.Cells[0].Text'. Put a breakpoint on the very next line and see what value you have there.

Resources