ASP/SQL Stored Procedure/ASP Function Error

Jul 20, 2007

Hey I have the following Stored Procedure


CREATE PROCEDURE spGetOrderCount
(
@search varchar(1000) = default
)

AS

SET NOCOUNT ON

/* Setup search string */
IF (@search <> '')
BEGIN
SET @search = 'WHERE' + @search
END


/* Create a temporary table */
CREATE TABLE #TempTable
(
row int IDENTITY,
totalCount int
)

/* Insert the search results into query */
EXEC
(
'INSERT INTO #TempTable([totalCount])' +
'SELECT COUNT(*) AS totalCount ' +
'FROM tblOrders' + @search
)

/* Extract the wanted records from the temporary table */
SELECT[totalCount],
RecordsLeft =
(
SELECT COUNT(*)
FROM #TempTable TI
)
FROM#TempTable

SET NOCOUNT OFF

RETURN
;
GO



And then the following function which specifies the where clause of the statement


function getOrderCount(strDate, strStatusList)
getOrderCount = 0
dim objRS, objSP, strWhereClause

if isDate(strDate) and len(strStatusList) > 0 then
'# Filter on order status



'# Filter on date clause
strWhereClause = "(tblOrders.orderDate >= " & sqlServerDate(strDate) & ")"

'#GET order count
Set objSP = SQLGetProcedure("spGetOrderCount")
SQLSetProcedureParam objSP, "search", strWhereClause

Set objRS = SQLExecuteProcedure(objSP)

if not objRS.eof then
getOrderCount = objRS("totalCount")
end if

'# Free resources
deleteRecordset(objRS)
deleteObject(objSP)
end if

end function


When I do this together I get the following error on my ASP Page

Microsoft OLE DB Provider for SQL Server error '80040e14'

Line 1: Incorrect syntax near '.'.

/sigma_eircommobdispatch/server/database.asp, line 235

And the print out of the resulting string from the function is

(tblOrders.orderDate >= CONVERT(DATETIME, '2007-7-13', 102))


If i remove the Where clause the statement works fine..

Any ideas

View 1 Replies


ADVERTISEMENT

Gridview / SqlDataSource Error - Procedure Or Function &<stored Procedure Name&> Has Too Many Arguments Specified.

Jan 19, 2007

Can someone help me with this issue? I am trying to update a record using a sp. The db table has an identity column. I seem to have set up everything correctly for Gridview and SqlDataSource but have no clue where my additional, phanton arguments are being generated. If I specify a custom statement rather than the stored procedure  in the Data Source configuration wizard I have no problem. But if I use a stored procedure I keep getting the error "Procedure or function <sp name> has too many arguments specified." But thing is, I didn't specify too many parameters, I specified exactly the number of parameters there are. I read through some posts and saw that the gridview datakey fields are automatically passed as parameters, but when I eliminate the ID parameter from the sp, from the SqlDataSource parameters list, or from both (ID is the datakey field for the gridview) and pray that .net somehow knows which record to update -- I still get the error. I'd like a simple solution, please, as I'm really new to this. What is wrong with this picture? Thank you very much for any light you can shed on this.

View 9 Replies View Related

Insert Stored Procedure With Error Check And Transaction Function

Jul 21, 2004

Hi, guys
I try to add some error check and transaction and rollback function on my insert stored procedure but I have an error "Error converting data type varchar to smalldatatime" if i don't use /*error check*/ code, everything went well and insert a row into contract table.
could you correct my code, if you know what is the problem?

thanks

My contract table DDL:
************************************************** ***

create table contract(
contractNum int identity(1,1) primary key,
contractDate smalldatetime not null,
tuition money not null,
studentId char(4) not null foreign key references student (studentId),
contactId int not null foreign key references contact (contactId)
);


My insert stored procedure is:
************************************************** *****

create proc sp_insert_new_contract
( @contractDate[smalldatetime],
@tuition [money],
@studentId[char](4),
@contactId[int])
as

if not exists (select studentid
from student
where studentid = @studentId)
begin
print 'studentid is not a valid id'
return -1
end

if not exists (select contactId
from contact
where contactId = @contactId)
begin
print 'contactid is not a valid id'
return -1
end
begin transaction

insert into contract
([contractDate],
[tuition],
[studentId],
[contactId])
values
(@contractDate,
@tuition,
@studentId,
@contactId)

/*Error Check */
if @@error !=0 or @@rowcount !=1
begin
rollback transaction
print ‘Insert is failed’
return -1
end
print ’New contract has been added’

commit transaction
return 0
go

View 1 Replies View Related

SqlDataSource.SelectParameters Causing Procedure Or Function Stored Procedure Has Too Many Arguments Specified.

Sep 12, 2006

 Hi everybody,   I am having trouble how to fixed this code. I am trying to supply the parameterinside a stored procedure with a value, and displays error message shown below. If I did not supply the parameter with a value, it works. How to fix this?Error Message:Procedure or function <stored proc name> has too many arguments specified.Thanks,den2005 
Stored procedure:

Alter PROCEDURE [dbo].[sp_GetIdeaByCategory]
@CatId <span class="kwd">int</span> = 0
AS
BEGIN
SET NOCOUNT ON;

Select I.*, C.*, U.* From Idea I inner join IdeaCategory C on I.CategoryID = C.IdeaCategoryID inner join Users U on I.UserID = U.UserID Where I.CategoryID = @CatId Order By LastModifiedDate Desc
End


oDataSource.ConnectionString = constr;
oDataSource.SelectCommand = storedProc;<span class="cmt">//storedproc - sp_GetIdeaByCategory</span>
oDataSource.SelectCommandType = SqlDataSourceCommandType.StoredProcedure;
oDataSource.SelectParameters.Add(<span class="st">&quot;@CatId&quot;</span>, catId);
gdvCategories.DataSourceID = oDataSource.ID;

gdvCategories.DataBind(); &lt;&lt;--- Error occured here


 

View 1 Replies View Related

Procedure Or Function 'stored Procedure Name' Expects Parameter Which Was Not Supplied

Mar 26, 2007

Has anyone encountered this before?
Procedure or Function 'stored procedure name' expects parameter '@parameter', which was not supplied.
It seems that my code is not passing the parameter to the stored procedure.
When I click this hyperlink:
<asp:HyperLink
ID="HyperLink1"
Runat="server"
NavigateUrl='<%# "../Division.aspx?CountryID=" + Eval("CountryID")%>'
Text='<%# Eval("Name") %>'
ToolTip='<%# Eval("Description") %>'
CssClass='<%# Eval("CountryID").ToString() == Request.QueryString["CountryID"] ? "CountrySelected" : "CountryUnselected" %>'>
</asp:HyperLink>
it is suppose to get the country name and description, based on the country id.
I am passing the country id like this.
protected void Page_Load(object sender, EventArgs e)
{
PopulateControls();
}
private void PopulateControls()
{
string countryId = Request.QueryString["CountryID"];
if (countryId != null)
{
CountryDetails cd = DivisionAccess.GetCountryDetails(countryId);
divisionNameLabel.Text = cd.Name;
divisionDescriptionLabel.Text = cd.Description;
}
}
To my app code like this:
public struct CountryDetails
{
public string Name;
public string Description;
}
public static class DivisionAccess
{
static DivisionAccess()
public static DataTable GetCountry()
{
DbCommand comm = GenericDataAccess.CreateCommand();
comm.CommandText = "GetCountry";
return GenericDataAccess.ExecuteSelectCommand(comm);
}
public static CountryDetails GetCountryDetails(string cId)
{
DbCommand comm = GenericDataAccess.CreateCommand();
comm.CommandText = "GetCountryDetails";
DbParameter param = comm.CreateParameter();
param.ParameterName = "@CountryID";
param.Value = 2;
param.DbType = DbType.Int32;
comm.Parameters.Add(param);
DataTable table = GenericDataAccess.ExecuteSelectCommand(comm);
CountryDetails details = new CountryDetails();
if (table.Rows.Count > 0)
{
details.Name = table.Rows[0]["Name"].ToString();
details.Description = table.Rows[0]["Description"].ToString();
}
return details;
}
 
As you can see I have two stored procedures I am calling, one does not have a parameter and the other does. The getcountry stored procedure returns the list of countries in a menu that I can click to see the details of that country. That is where my problem is when I click the country name I get
Procedure or Function 'GetCountryDetails' expects parameter '@CountryID', which was not supplied
Someone please help!
 
Thanks Nickdel68

View 5 Replies View Related

Calling A Stored Procedure Or Function From Another Stored Procedure

Mar 2, 2007

Hello people,

When I am trying to call a function I made from a stored procedure of my creation as well I am getting:

Running [dbo].[DeleteSetByTime].

Cannot find either column "dbo" or the user-defined function or aggregate "dbo.TTLValue", or the name is ambiguous.

No rows affected.

(0 row(s) returned)

@RETURN_VALUE =

Finished running [dbo].[DeleteSetByTime].

This is my function:

ALTER FUNCTION dbo.TTLValue

(

)

RETURNS TABLE

AS

RETURN SELECT Settings.TTL FROM Settings WHERE Enabled='true'

This is my stored procedure:

ALTER PROCEDURE dbo.DeleteSetByTime

AS

BEGIN



SET NOCOUNT ON



DECLARE @TTL int

SET @TTL = dbo.TTLValue()



DELETE FROM SetValues WHERE CreatedTime > dateadd(minute, @TTL, CreatedTime)

END

CreatedTime is a datetime column and TTL is an integer column.

I tried calling it by dbo.TTLValue(), dbo.MyDatabase.TTLValue(), [dbo].[MyDatabase].[TTLValue]() and TTLValue(). The last returned an error when saving it "'TTLValue' is not a recognized built-in function name". Can anybody tell me how to call this function from my stored procedure? Also, if anybody knows of a good book or site with tutorials on how to become a pro in T-SQL I will appreciate it.

Your help is much appreciated.

View 6 Replies View Related

Function Vs Stored Procedure

May 1, 2004

I know this is a stupid question (actually, maybe its not..?)

They seem to be identical in some ways, but not available to the outside world. what are some differences?

View 3 Replies View Related

Function From Stored Procedure

Nov 22, 2007

Hi Everyone,

i want to create a function in Stored procedure and then call this function
that returns true or false from a stored procedure .
is this possible?

please help me if you know something that can help me.

thanks

Tvin

View 2 Replies View Related

When To Use A Function And When To Use A Stored Procedure.

Oct 28, 2006

Hi,

I thought that procedures do not return a value: well they only return a 1 or 0 depending on whether the procedure executed correctly. Functions are what you're supposed to use when you want to get a result set of some sort: ie a table or a scalar value.

Apparently that is not the case becuase you can return values from procedures. I've attempted to find out what the differences are between the two and when it is appropriate to use a procedure and when it is appropriate to use a function but I'm still unsure. Can someone please tell me the difference.

Thanks.

Przemek

View 16 Replies View Related

Differance Stored Procedure And Function

Nov 26, 2006

hello
what is differance beetween stored-procedure and Function
when use of stored rpocedure and function

View 1 Replies View Related

Call Function From Stored Procedure

Jan 19, 2007

Hi All,
I'll admit that I'm not the greatest at stored procedure/functions but I want to learn as much as possible.  So I have two questions:
1) I had VS2005 autogenerate a sqldatasource that created Select/Insert/Update stored procedures.  When Updating a record and calling the stored procedure, I want to query another table (we'll call it tblBatchNo) that has only one record, Batchno.  I want to put that current batchno into the Update statement and update the record with the current batchno.  Can someone point me in the right direction?  Remember that I'm still a beginner on this subject.
2) Can someone provide any links to online tutorials on t-sql?
Thanks in advance.
Curtis

View 2 Replies View Related

Calling A Function From A Stored Procedure

Oct 26, 2007

Hello all,
I'm trying to construct a select statement in a stored procedure that filters based on the returned values of a number of functions.  My function works fine, but when I try to call the function from the stored procedure I get an error.
I'm going to try explain the thought process behind what I'm doing.  Hope I make enough sense.The purpose of the stored procedure is to perform a wildcard search on a tool.  The tool contains a number of FK that link to different tables (e.g., manufacturer, vendor).  So I'm creating functions that also search the manufacturer and vendor and return the matching IDs.
Example of tool SELECT statement:SELECT tool_number, tool_description
FROM tool
WHERE tool_manufacturer IN (UDFmanufacturer_SearchName(@search_string)
This gives me an error:'UDFmanufacturer_SearchName' is not a recognized built-in function name.
Function code (removed some wrapping code for simplicity):SELECT manufacturer_id
FROM manufacturer
WHERE manufacturer_name LIKE '%' + @search_string + '%'These statements both work if I run a independent query: SELECT *
FROM UDFmanufacturer_SearchName('mol')  SELECT *
FROM tool
WHERE tool_manufacturer IN (SELECT *FROM UDFmanufacturer_SearchName('mol')) This code fails:SELECT *
FROM ato_tool
WHERE ato_tool_manufacturer IN (UDFmanufacturer_SearchName('mol'))
 I'm stuck.  I haven't been able to find anything that shows me where I'm going wrong.  Any thoughts or suggestions are appreciated. Thanks,Jay

View 4 Replies View Related

Stored Procedure - Date Function

Jul 28, 2005

Hi, I ran into some problem here. The case scenerio is supposed to be like this:

- Each member can only make one appointment at any one time and only
make another appointment after the existing appointment expired.
- Each member is allowed to make an appointment at any time and must be at least 5 days in advance.

I managed to do the reservation for at least 5 days in advance but I
can't allow the member to make only one appointment. The member can
keep making appointments even though the existing appointment has not
expired. Can someone pls help? Thanks!


ALTER PROCEDURE spReserveAppt(@AppDate DATETIME, @AppTime CHAR(4), @MemNRIC CHAR(9))
AS

BEGIN
IF NOT EXISTS(SELECT MemNRIC FROM DasMember WHERE MemNRIC = @MemNRIC)
    RETURN -300

BEGIN
IF EXISTS
     (SELECT COUNT(@MemNRIC)
    FROM DasAppointment   
    WHERE (DATEDIFF(DAY, GETDATE(), @AppDate) < 5)
    GROUP BY MemNRIC
    HAVING COUNT(@MemNRIC) <> 0)
    RETURN -301

ELSE IF EXISTS
    (SELECT MemNRIC
    FROM DasAppointment   
    WHERE (DATEDIFF(DAY, @AppDate ,GETDATE()) > GETDATE()))
    RETURN -302

END
END

INSERT INTO DasAppointment(AppDate, AppTime, MemNRIC) VALUES (@AppDate, @AppTime, @MemNRIC)

IF @@ERROR <> 0
    RETURN @@ERROR

RETURN

DECLARE @status int
EXEC @status = spReserveAppt '2005-08-16', '1900', 'S1256755J'
SELECT 'Status' = @status

View 2 Replies View Related

How To Call A Function In Stored Procedure

Sep 12, 2012

How to call a sql function in stored procedure using Sqlserver 2008?

View 4 Replies View Related

RESOLVED: Stored Procedure Of Function?

Aug 16, 2006

I have a select statement like this. Notice that I am doing the same calculation on different fields. Is it possible I can make this, in coding terms, a fucntion; so I can call it when I like (this query) and just provide the field.

Example: select field1, test_field = secs_to_hhmmss(TALK_TIME) from ...

SELECT dbo.date_table.real_date, dbo.time_table.hh,
COUNT(dbo.CALLDETAIL.id) as NumOfCalls,
TalkTime =
CASE WHEN CAST(SUM(TALK_TIME) AS INTEGER)/3600<10 THEN '0' ELSE '' END
+ RTRIM(CAST(SUM(TALK_TIME) AS INTEGER)/3600)
+ ':' + RIGHT('0'+RTRIM((CAST(SUM(TALK_TIME) AS INTEGER) % 3600) / 60),2)
+ ':' + RIGHT('0'+RTRIM((CAST(SUM(TALK_TIME) AS INTEGER) % 3600) % 60),2),
HoldTime =
CASE WHEN CAST(SUM(HOLD_TIME) AS INTEGER)/3600<10 THEN '0' ELSE '' END
+ RTRIM(CAST(SUM(HOLD_TIME) AS INTEGER)/3600)
+ ':' + RIGHT('0'+RTRIM((CAST(SUM(HOLD_TIME) AS INTEGER) % 3600) / 60),2)
+ ':' + RIGHT('0'+RTRIM((CAST(SUM(HOLD_TIME) AS INTEGER) % 3600) % 60),2),

View 3 Replies View Related

Use Function From Asp File In Stored Procedure

Jul 23, 2005

Hello everybody,I have a file with several asp functions where some depend on others.Some of the functions I will need to transform a string value.How can I include these functions in a stored procedure? (in SqlServer 2000)Do I have to add all the functions as userdefined functions?Or is possible to reference the external file like include files inasp?Thank you for your help!Regards,Michael

View 3 Replies View Related

Using A Function To Pass A Parameter To A Stored Procedure

Apr 3, 2007

In the snippet below,  ExecuteSqlString is a stored procedure that accepts one parameter.  SelectChangeDropdownRowsource is a function in my code behind page that generates the string I want to pass.  I can't seem to find the correct syntax to get it to work.  The way it is show below, the error comes back about incorrect syntax near ')' .  Is this doable? 
<asp:SqlDataSource ID="ChangeInfo" runat="server" ConnectionString="<%$ ConnectionStrings:xxx %>"
DataSourceMode="DataReader" ProviderName="<%$ ConnectionStrings:xxx %>"
SelectCommandType=StoredProcedure
SelectCommand="ExecuteSqlString">
<selectparameters>
<asp:parameter name="sqlString" Type=String DefaultValue=SelectChangeDropdownRowsource()/>
</selectparameters>
</asp:SqlDataSource>

View 6 Replies View Related

Diff Betn Function And Stored Procedure

May 22, 2008

Hii , can anyone tell me the difference of using function and stored procedure and similarity between them... 

View 2 Replies View Related

User-Defined-Function With-in Stored-Procedure??

Apr 14, 2008

Does MS-SQL allow us to create an user-defined function within the stored-procedure script? I have been getting errors. It's my first time using the user-defined function with stored-procedure. I welcome your help.


Code:


CREATE FUNCTION ftnVehicleYearFormattor (@sValue VARCHAR(2))
RETURNS VARCHAR(2)
AS
BEGIN
IF (LEN(@sValue) < 2)
SET @sValue = '0' + @sValue

RETURN @sValue
END



Thanks...

View 4 Replies View Related

Maximum Stored Procedure, Function, Trigger, Or Vi

Mar 7, 2008

HI ALL,
I AM USING SQL SERVER 2005.
I HAVE RETURN A RECURSIVE FUNCTION TO FIND OUT WHETHER THE NEXT DATE DOES NOT FALL WITHIN HOLIDAYS
BUT I AM GETING THIS ERROR
Maximum stored procedure, function, trigger, or view nesting level exceeded (limit 32).

THE CODE I USED IS


alter FUNCTION [dbo].[GetNextDay](@dt datetime , @empcode varchar(50) )
RETURNS datetime
AS
BEGIN
DECLARE @zoneid VARCHAR(50)
declare @lvlflag varchar(50)
declare @utdt DATETIME
DECLARE @RETDT DATETIME
DECLARE @COMPDT DATETIME


Select @lvlflag= b.ulm_user_field_flag from bbraun_emis.dbo.emp_reference a join bbraun_emis.dbo.user_lvl_master b on b.ulm_user_lvl_id = a.ER_USER_LVL and a.er_emp_code = @empcode
SELECT @zoneid = ZONECODE FROM bbraun_emis.dbo.VWREGIONLINK WHERE CITYCODE IN (SELECT DISTINCT HM_CITY_CODE FROM bbraun_emis.dbo.HOSP_MASTER WHERE HM_HOSP_CODE IN (SELECT HER_HOSP_CODE FROM bbraun_emis.dbo.HOSP_EMP_REL WHERE HER_EMP_CODE in(@EMPCODE)))
select @compdt = holiday_date from oriffconnect.dbo.holiday_master where zone_code = @zoneid and field_staff = @lvlflag and holiday_date = @dt

if(@@ROWCOUNT = 0)
begin

Select @utdt = DATEADD(dd,1,@utdt)
SeT @utdt = ([dbo].[GetNextDay](@utdt , @empcode))
end
IF(@@ROWCOUNT <> 0)
begin
set @utdt = @dt
end
Select @RETDT = @utdt
RETURN @RETDT

END




PLEASE HELP

View 2 Replies View Related

Stored Procedure - User Defined Function.

Jul 20, 2005

Hi.I'm really new to MSSQL, so therefore my question can sound stupid.Is it possible to use a function written in a module in MS-ACCESS in astored procedure?Or how can it be done, it is a complicated function with loop and more.I'll appreciate all answers also negatives ones.TIAJørn

View 1 Replies View Related

How To Use User Defined Function In Stored Procedure?

Mar 14, 2006

Hello friends,

I want to use my user defined function in a stored procedure.

I have used it like ,

select statement where id = dbo.getid(1,1,'abc')

//dbo.getid is a user defined function.



procedure is created successfully but when i run it by exec procedurename parameter



I get error that says

"Cannot find either column "dbo" or the user-defined function or aggregate "dbo.getid", or the name is ambiguous."


Can any body help me?



Rgds,

Kiran.

View 3 Replies View Related

Stored Procedure And Calling User Defined Function

Sep 29, 2007

I seem to be getting tasks that I am not familiar with these days. I am a
guy that has coded it all in the asp page or in the code behind in .NET.
This problem is outlined below and I need a help / advice on doing this. I
had the flow of the 3 parts to it expanded below. A call is made to a Stored
Procedure, The SP then calls a user defined function that runs SQL, this
returns a 1 or 0 to the SP which then returns the value back to the call on
the asp page. This is a lot I know but it is the way the lead guy wants it
done. Any help so I can keep most of the hair I have left is appreciated :-)

Short list of process flow:

1. Form.asp calls to rx_sp_HasAccessToClient in SQL SERVER

2. rx_sp_HasAccessToClient then calls ab_HasAccessToClient

3. ab_HasAccessToClient runs SQL command on db and sends return bit back to
rx_sp_HasAccessToClient

4. rx_sp_HasAccessToClient then sends this back to the call in the Form.asp
page

5. Form.asp then checks the Boolean and if 1 then show or if 0 then deny.

<FLOW WITH CODE AND FUNCTIONS :>

This is not the correct syntax but is showing what I understand sort of how
this is to be done so far.

This panel loads up the Vendors and id's when the user clicks on the link
"view detailed list of vendors associated with this client". This is the
beginning of the process.

This is code in Form.asp

'PANEL ONE
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXX----
>

If ValidateInput(Request.Querystring("Postback"))="FormDetails" then 'Check
Postback Type

'We need to load up vendors associated with the current client.

'--------- CHECK ACCESS HERE via function ab_HasAccessToClient
--------

'If the call returns 1, then the employee has access.

'Otherwise, just write out "Access to this client is denied."

'CALL SP - Not sure what parameters need to go with it or its syntax

Execute_SP("rx_sp_HasAccessToClient '" & ClientSSN & "', 1)

'When it returns can check it here........

if ab_HasAccessToClient result is a 1 then

'boolean would be 1 so show panel

Else

'boolean would be 0 so show access denied

'allow them to go back to the original page.

end if

'PANEL ONE
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXX----
>

ON SQL SERVER: Stored Procedure

----------------------------------------------------------
--------------------------------

rx_sp_HasAccessToClient

CREATE PROCEDURE [dbo].[ rx_sp_HasAccessToClient]

@EmployeeID INT,

@ClientSSN varchar(50),

@ReturnBitValue = OUTPUT

/*

' Parameters here passed via call from Form.asp - not sure what is passed
yet.

*/

AS

set nocount on

/*

Written by Mike Belcher 9/27/2007 for Form.asp

'Calls ab_HasAccessToClient function - not sure of the syntax as of yet,
just making flow.

'Gets return bit and passes that back to the call from Form.asp

*/

GO

----------------------------------------------------------
--------------------------------

ON SQL SERVER: User-Defined Function

----------------------------------------------------------
--------------------------------

ab_HasAccessToClient

CREATE FUNCTION ab_HasAccessToClient (@employeeID INT, @ClientSSN
VARCHAR(50))

@ClientSSN varchar(50),

@EmployeeID,

@ReturnBitValue = OUTPUT

AS

SELECT 1

FROM tblEmployeesClients ec

INNER JOIN tblClients c ON ec.ClientID = c.ClientSSN

INNER JOIN tblEmployees e ON ec.Employee = e.EmployeeLogInName

WHERE e.EmployeeID= @EmployeeID

AND c.InActiveClient=0

AND c.ClientSSN = @ClientSSN

'Some Code here to save result bit ..

RETURN @ReturnBitValue 'Back to rx_sp_HasAccessToClient

----------------------------------------------------------
--------------------------------

</FLOW WITH CODE AND FUNCTIONS :>

View 5 Replies View Related

Stored Procedure - Field Not In Aggregate Function Or Group By

Nov 29, 2011

best solution for this stored procedure query.I'm getting the following error:

Column 'dbo.Applicants.submitted' is invalid in the select list because it is not contained in an aggregate function and there is no GROUP BY clause. Here is my select query:

Code:
SELECT DISTINCT DATENAME(MONTH, submitted) AS mon, MAX(submitted) AS SubmitDate
FROM dbo.Applicants
WHERE ((CASE WHEN MONTH(submitted) > 8 THEN YEAR(submitted) + 1 ELSE YEAR(submitted) END) = @AcYr)
ORDER BY SubmitDate

The submitted field is a date field.I don't want to add the submitted field to Group By as I want to group by month not date.Is there any solution to avoid grouping by date?

View 3 Replies View Related

Stored Procedure And Calling User Defined Function

Sep 29, 2007

I seem to be getting tasks that I am not familiar with these days. I am a
guy that has coded it all in the asp page or in the code behind in .NET.
This problem is outlined below and I need a help / advice on doing this. I
had the flow of the 3 parts to it expanded below. A call is made to a Stored
Procedure, The SP then calls a user defined function that runs SQL, this
returns a 1 or 0 to the SP which then returns the value back to the call on
the asp page. This is a lot I know but it is the way the lead guy wants it
done. Any help so I can keep most of the hair I have left is appreciated :-)

Short list of process flow:

1. Form.asp calls to rx_sp_HasAccessToClient in SQL SERVER

2. rx_sp_HasAccessToClient then calls ab_HasAccessToClient

3. ab_HasAccessToClient runs SQL command on db and sends return bit back to
rx_sp_HasAccessToClient

4. rx_sp_HasAccessToClient then sends this back to the call in the Form.asp
page

5. Form.asp then checks the Boolean and if 1 then show or if 0 then deny.

<FLOW WITH CODE AND FUNCTIONS :>

This is not the correct syntax but is showing what I understand sort of how
this is to be done so far.

This panel loads up the Vendors and id's when the user clicks on the link
"view detailed list of vendors associated with this client". This is the
beginning of the process.

This is code in Form.asp

'PANEL ONE
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXX----
>

If ValidateInput(Request.Querystring("Postback"))="Fo rmDetails" then 'Check
Postback Type

'We need to load up vendors associated with the current client.

'--------- CHECK ACCESS HERE via function ab_HasAccessToClient
--------

'If the call returns 1, then the employee has access.

'Otherwise, just write out "Access to this client is denied."

'CALL SP - Not sure what parameters need to go with it or its syntax

Execute_SP("rx_sp_HasAccessToClient '" & ClientSSN & "', 1)

'When it returns can check it here........

if ab_HasAccessToClient result is a 1 then

'boolean would be 1 so show panel

Else

'boolean would be 0 so show access denied

'allow them to go back to the original page.

end if

'PANEL ONE
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXX----
>

ON SQL SERVER: Stored Procedure

----------------------------------------------------------
--------------------------------

rx_sp_HasAccessToClient

CREATE PROCEDURE [dbo].[ rx_sp_HasAccessToClient]

@EmployeeID INT,

@ClientSSN varchar(50),

@ReturnBitValue = OUTPUT

/*

' Parameters here passed via call from Form.asp - not sure what is passed
yet.

*/

AS

set nocount on

/*

Written by Mike Belcher 9/27/2007 for Form.asp

'Calls ab_HasAccessToClient function - not sure of the syntax as of yet,
just making flow.

'Gets return bit and passes that back to the call from Form.asp

*/

GO

----------------------------------------------------------
--------------------------------

ON SQL SERVER: User-Defined Function

----------------------------------------------------------
--------------------------------

ab_HasAccessToClient

CREATE FUNCTION ab_HasAccessToClient (@employeeID INT, @ClientSSN
VARCHAR(50))

@ClientSSN varchar(50),

@EmployeeID,

@ReturnBitValue = OUTPUT

AS

SELECT 1

FROM tblEmployeesClients ec

INNER JOIN tblClients c ON ec.ClientID = c.ClientSSN

INNER JOIN tblEmployees e ON ec.Employee = e.EmployeeLogInName

WHERE e.EmployeeID= @EmployeeID

AND c.InActiveClient=0

AND c.ClientSSN = @ClientSSN

'Some Code here to save result bit ..

RETURN @ReturnBitValue 'Back to rx_sp_HasAccessToClient

----------------------------------------------------------
--------------------------------

</FLOW WITH CODE AND FUNCTIONS :>

View 1 Replies View Related

Extended Stored Procedure Problem (srv_describe Function)...

Jul 20, 2005

Hello all,I have spend quite some time now but don't manage tofind out how to have the srv_describe function workingproperly for target NUMERIC(x,x) and NUMERIC types.Already tried several alternatives like e.g.// ...PVOID pvdata1;strcpy((char*)pvdata1, "12345.6789");wsprintf(colname, "Score");srv_describe(srvproc, 1 /* column #1 */, colname /* column name */, SRV_NULLTERM /* column name ending */, SRVNUMERIC, (DBINT)sizeof(DBNUMERIC), SRVNUMERIC, (DBINT)sizeof(DBNUMERIC), pvdata1);srv_setcoldata(srvproc, 1, pvdata1);srv_setcollen (srvproc, 1, strlen((char*)pvdata1));// ...but obviously does not work, I get an empty resultset.I could only manage by converting the numeric valueto string from C and then sending only strings but theSQL side expects actually a number(x,x) and is a customer, in which case, I would never propose to be casting thething from TSQL.Any ideas how to do it? The documentation and examples isquite limited in this area.Thanks in advance,Best Regards,Giovanni

View 2 Replies View Related

Calling User Defined Function From Stored Procedure

Jul 30, 2007

When i call user defined function from stored procedure, i am getting an error.

[Microsoft][ODBC SQL Server Driver][SQL Server]Invalid object name 'dbo.MyFunction'.


why this error is happening?.

i am calling this way... dbo.MyFunction(param1,param2)

View 6 Replies View Related

SSIS-Use Stored Procedure/function As The Data Source

Jan 28, 2008



How do I use stored procedure or a user defined function as the data source in my SSIS package.
I am very new to SSIS.
Thanks

View 5 Replies View Related

User Defined Function To Stored Procedure Call?

Apr 7, 2008

Hello,

Can we call stored procedure from user defined function and vice-versa??

Thanks in advance.

View 4 Replies View Related

Stored Procedure And Function To Add Hashbyte (chksum) To Be Able To Do Delta Processing

Feb 5, 2015

function

/*Title:
Created By:
Create Date:
Notes:This function is used to concatenate the fields of a table except any identity and hashbyte column passed into the function. It works for temp tables are phyisical tables.

** NOTE: The temp table has be on the same SQL connection to work. If you use this in SSIS you will need to make your connection persistant.

The original concept came from [URL] .... and was modified.

Revisions:

*/
ALTER FUNCTION [dbo].[get_hash_fields] ( @p_table_name VARCHAR(128),
@p_schema_name VARCHAR(20),
@chksum_col_name varchar(255) )
RETURNS VARCHAR(MAX)
AS
BEGIN
DECLARE @sqlString as varchar(max)

[Code] ....

View 0 Replies View Related

Strange Problew With User Defined Function Or Stored Procedure

Jul 23, 2005

I am trying to add a simple case statement to a stored procedure oruser defined function. However when I try and save thefunction/procedure I get 2 syntax errors. Running the query in queryanalyser works fine and a result is given with no syntax errors. Ibelieve its something to do with the spaces in the field names. Not mychoice as its an existing system I have to work around. Any helpgreatly appreciatedSQL QueryDECLARE @pfid VARCHAR(100)SET @pfid = '000101'SELECTCaseWHEN GetDate()BETWEEN gg_shop_product.sale_start AND gg_shop_product.sale_endTHEN((((gg_shop_product.Sale_Price/100)/1.175)-("dbo"."Navision_Cost_Prices"."Unit Cost" *Navision_Codes."Navision QTY"))/((gg_shop_product.Sale_Price/100)/1.175)) * 100WHEN dbo.Navision_Cost_Prices."Unit Cost" = 0Then '100'WHEN gg_shop_product.list_price > 0 THEN((((gg_shop_product.List_Price /100)/1.175)-("dbo"."Navision_Cost_Prices"."UnitCost"*dbo.Navision_Codes."NavisionQTY"))/((gg_shop_product.List_Price/100)/ 1.175)) * 100END as 'Margin'from gg_shop_product INNER JOINgg_shop_variant ON gg_shop_product.pf_id =gg_shop_variant.pf_id LEFT OUTER JOINgg_shop_cost_prices ON gg_shop_product.pf_id =gg_shop_cost_prices.pf_id INNER JOINNavision_Codes ON gg_shop_variant.sku = Navision_Codes.skuINNER JOIN NAVISION_Cost_Prices ON Navision_Codes."Navision No" =Navision_Cost_Prices.NoWHERE gg_shop_product.pf_id = @pfidUser Defined Function (Errors Line 11 & 15)CREATE FUNCTION dbo.get_Margin(@pfid VARCHAR(100), @dtNow DATETIME)RETURNS DECIMAL ASBEGINDECLARE @Return as DECIMALSET @Return = (SELECTCaseWHEN @dtNowBETWEEN gg_shop_product.sale_start AND gg_shop_product.sale_endTHEN((((gg_shop_product.Sale_Price/100)/1.175)-(dbo.Navision_Cost_Prices."Unit Cost" *Navision_Codes."Navision QTY"))/((gg_shop_product.Sale_Price/100)/1.175)) * 100WHEN dbo.Navision_Cost_Prices."Unit Cost" = 0Then '100'WHEN gg_shop_product.list_price > 0 THEN((((gg_shop_product.List_Price /100)/1.175)-("dbo"."Navision_Cost_Prices"."UnitCost"*dbo.Navision_Codes."NavisionQTY"))/((gg_shop_product.List_Price/100)/ 1.175)) * 100END as 'Margin'from gg_shop_product INNER JOINgg_shop_variant ON gg_shop_product.pf_id =gg_shop_variant.pf_id LEFT OUTER JOINgg_shop_cost_prices ON gg_shop_product.pf_id =gg_shop_cost_prices.pf_id INNER JOINNavision_Codes ON gg_shop_variant.sku = Navision_Codes.skuINNER JOIN NAVISION_Cost_Prices ON Navision_Codes."Navision No" =Navision_Cost_Prices.NoWHERE gg_shop_product.pf_id = @pfid)RETURN @ReturnEND

View 3 Replies View Related

Can A Stored Procedure Called From An Inline Table-Valued Function

Oct 5, 2006

Hi,

I'm trying to call a Stored Procedure from a Inline Table-Valued Function. Is it possible? If so can someone please tell me how? And also I would like to call this function from a view. Can it be possible? Any help is highly appreciated. Thanks

View 4 Replies View Related

Error: Procedure Or Function Has Too Many Arguments Specified

Dec 9, 2005

Hi,

I've found that I'm not the first one to get the error

"Procedure or function x has too many arguments specified"

while working with Stored Procedures (which is no surprise at all). But
all suggested solutions didn't help, maybe this is because I
misunderstood the whole concept. The situation is: On my page there is
a FormView control including the EditItemTemplate. The database
contains a Stored Procedure called UpdatePersonByID which is working
fine as long as executed in Visual Web Developer. Here's the procedure
code:

ALTER PROCEDURE dbo.UpdatePersonByID
    (
        @LastName varchar(50),
        @FirstName varchar(50),
        @Phone varchar(50),
        @PhonePrivate varchar(50),
        @PhoneMobile varchar(50),
        @Email varchar(50)
    )
AS
    UPDATE
        tblPersons
        SET
            PersonLastName = @LastName,
            PersonFirstName = @FirstName,
            PersonPhone = @Phone,
            PersonPhonePrivate = @PhonePrivate,
            PersonPhoneMobile = @PhoneMobile,
            PersonEmail = @Email
        WHERE
            PersonLastName = @LastName
    RETURN

This is not exactly what it will finally have to do, of course the
WHERE-clause later will contain an ID comparison. But since I tried to
break down my code as much as possible I changed it to what you see
right now. Here's the aspx-source (the red stuff is what I think is
important):

<%@ Page
    Language="VB"
    MasterPageFile="fb10.master"
    AutoEventWireup="false"
    CodeFile="codebehind/staff.aspx.vb"
    Inherits="staff"
    meta:ResourceKey="PageResource"
%>
<%@ MasterType VirtualPath ="~/fb10.master"  %>
<asp:Content
    ID="ContentStaff"
    ContentPlaceHolderID="cphContentMain"
    Runat="Server">
   
    <h3 id="hdStaff" runat="server" meta:resourcekey="Staff" />

    <!-- DataSource srcStaff collects all persons from staff table in database. -->
    <asp:SqlDataSource
        ID="srcStaff"
        runat="server"
        ConflictDetection="CompareAllValues"
        ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
        SelectCommandType="StoredProcedure"
        SelectCommand="SelectPersonNames"
    />
    <asp:DropDownList
        ID="ddlStaff"
        runat="server"
        DataSourceID="srcStaff"
        DataTextField="CompleteName"
        DataValueField="PersonID"
        AutoPostBack="True">
    </asp:DropDownList>

    <!-- DataSource srcPerson gets person selected in DropDownList "ddlStaff". -->
    <asp:SqlDataSource
        ID="srcPerson"
        runat="server"
        ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
        ProviderName="System.Data.SqlClient"
        SelectCommand="SelectPersonByID"
        SelectCommandType="StoredProcedure"
        UpdateCommand="UpdatePersonByID"
        UpdateCommandType="StoredProcedure"
        OldValuesParameterFormatString="{0}" >
        <SelectParameters>
            <asp:ControlParameter
                ControlID="ddlStaff"
                DefaultValue="1"
                Name="ID"
                PropertyName="SelectedValue"
                Type="Int32" />
        </SelectParameters>
        <UpdateParameters>
            <asp:Parameter Name="LastName" Type="String" />
            <asp:Parameter Name="FirstName" Type="String" />
            <asp:Parameter Name="Phone" Type="String" />
            <asp:Parameter Name="PhonePrivate" Type="String" />
            <asp:Parameter Name="PhoneMobile" Type="String" />
            <asp:Parameter Name="Email" Type="String" />
        </UpdateParameters>
    </asp:SqlDataSource>

    <!--  DataSource srcBuildings gets all buildings from building table in database. -->
    <asp:SqlDataSource
        ID="srcBuildings"
        runat="server"
        ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
        ProviderName="System.Data.SqlClient"
        SelectCommand="SelectBuildings"
        SelectCommandType="StoredProcedure">
    </asp:SqlDataSource>
   
    <asp:FormView
        ID="fvStaff"
        runat="server"
        DataSourceID="srcPerson">
        <EditItemTemplate>
            <!--
DataSource srcRooms gets all rooms from room table in database. -->
            <asp:SqlDataSource
                ID="srcRooms"
                runat="server"
   
           
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
                ProviderName="System.Data.SqlClient"
                SelectCommand="SelectRoomsByBuildingID"
                SelectCommandType="StoredProcedure">
                <SelectParameters>
                    <asp:ControlParameter
           
           
ControlID="ddlBuildings"
           
           
DefaultValue="1"
           
           
Name="ID"
           
           
PropertyName="SelectedValue"
           
           
Type="Int32"
                    />
                </SelectParameters>
            </asp:SqlDataSource>

            <asp:Label
cssClass="lblIdentifier" ID="lblLastName" runat="server"
meta:resourcekey="LastName" />
           
<asp:TextBox cssClass="staff" ID="LastName" runat="server"
Text='<%# Bind("PersonLastName")
%>'></asp:TextBox><br />

            <asp:Label
cssClass="lblIdentifier" ID="lblFirstName" runat="server"
meta:resourcekey="FirstName" />
           
<asp:TextBox cssClass="staff" ID="FirstName" runat="server"
Text='<%# Bind("PersonFirstName")
%>'></asp:TextBox><br />
           
            <asp:Label
CssClass="lblIdentifier" ID="lblBuilding" runat="server"
meta:resourcekey="Building"></asp:Label>
            <asp:DropDownList
                ID="ddlBuildings"
                cssClass="small"
                runat="server"
                DataSourceID="srcBuildings"
                DataTextField="BuildingAbbreviation"
                DataValueField="BuildingID"
                AutoPostBack="True"
                SelectedValue='<%# Bind("RoomBuildingID") %>'
           
   
OnSelectedIndexChanged="ddlBuildings_SelectedIndexChanged">
            </asp:DropDownList><br />
           
            <asp:Label
cssClass="lblIdentifier" ID="lblRoom" runat="server"
meta:resourcekey="Room" />
            <asp:DropDownList
                ID="ddlRooms"
                cssClass="small"
                runat="server"
                DataSourceID="srcRooms"
                DataTextField="RoomName"
                DataValueField="RoomID"
                AutoPostBack="true"
           
    SelectedValue='<%# Bind("PersonRoomID") %>'>
            </asp:DropDownList><br />

            <asp:Label
cssClass="lblIdentifier" ID="lblPhone" runat="server"
meta:resourcekey="Phone" />
           
<asp:TextBox cssClass="staff" ID="Phone" runat="server" Text='<%#
Bind("PersonPhone") %>'></asp:TextBox><br />
           
            <asp:Label
cssClass="lblIdentifier" ID="lblPhonePrivate" runat="server"
meta:resourcekey="Private" />
           
<asp:TextBox cssClass="staff" ID="PhonePrivate" runat="server"
Text='<%# Bind("PersonPhonePrivate")
%>'></asp:TextBox><br />
           
            <asp:Label
cssClass="lblIdentifier" ID="lblPhoneMobile" runat="server"
meta:resourcekey="Mobile" />
           
<asp:TextBox cssClass="staff" ID="PhoneMobile" runat="server"
Text='<%# Bind("PersonPhoneMobile")
%>'></asp:TextBox><br />

            <asp:Label
cssClass="lblIdentifier" ID="lblEmail" runat="server"
meta:resourcekey="Email" />
           
<asp:TextBox cssClass="staff" ID="Email" runat="server" Text='<%#
Bind("PersonEmail") %>'></asp:TextBox><br />

           
<asp:LinkButton cssClass="lnkButton" ID="UpdateCancelButton"
runat="server" CausesValidation="False" CommandName="Cancel"
Text="<%$resources:translations,
Cancel%>"></asp:LinkButton>
           
<asp:LinkButton cssClass="lnkButton" ID="UpdateButton"
runat="server" CausesValidation="True" CommandName="Update"
Text="<%$resources:translations,
Update%>"></asp:LinkButton>
        </EditItemTemplate>
        <InsertItemTemplate>
            <asp:Label
cssClass="lblIdentifier" ID="lblLastName" runat="server"
meta:resourcekey="LastName" />
           
<asp:TextBox ID="PersonLastNameTextBox"
runat="server"></asp:TextBox><br />
           
            <asp:Label
cssClass="lblIdentifier" ID="lblFirstName" runat="server"
meta:resourcekey="FirstName" />
           
<asp:TextBox ID="PersonFirstNameTextBox"
runat="server"></asp:TextBox><br />
           
            <asp:Label
cssClass="lblIdentifier" ID="lblBuilding" runat="server"
meta:resourcekey="Building" />
           
<asp:TextBox ID="BuildingAbbreviationTextBox"
runat="server"></asp:TextBox><br />
           
            <asp:Label
cssClass="lblIdentifier" ID="lblRoom" runat="server"
meta:resourcekey="Room" />
           
<asp:TextBox ID="RoomNameTextBox"
runat="server"></asp:TextBox><br />
           
           
<asp:LinkButton cssClass="lnkButton" ID="InsertCancelButton"
runat="server" CausesValidation="False" CommandName="Cancel"
Text="<%$resources:translations,
Cancel%>"></asp:LinkButton>
           
<asp:LinkButton cssClass="lnkButton" ID="InsertButton"
runat="server" CausesValidation="True" CommandName="Insert"
Text="<%$resources:translations,
Insert%>"></asp:LinkButton>
        </InsertItemTemplate>
        <ItemTemplate>
            <asp:Label
cssClass="lblIdentifier" ID="lblLastName" runat="server"
meta:resourcekey="LastName" />
            <asp:Label
cssClass="lblValue" ID="PersonLastNameLabel" runat="server"
Text='<%# Bind("PersonLastName") %>'></asp:Label><br
/>

            <asp:Label
cssClass="lblIdentifier" ID="lblFirstName" runat="server"
meta:resourcekey="FirstName" />
            <asp:Label
cssClass="lblValue" ID="PersonFirstNameLabel" runat="server"
Text='<%# Bind("PersonFirstName") %>'></asp:Label><br
/>

            <asp:Label
cssClass="lblIdentifier" ID="lblBuilding" runat="server"
meta:resourcekey="Building" />
            <asp:Label
cssClass="lblValue" ID="BuildingAbbreviationLabel" runat="server"
Text='<%# Bind("BuildingAbbreviation")
%>'></asp:Label><br />

            <asp:Label
cssClass="lblIdentifier" ID="lblRoom" runat="server"
meta:resourcekey="Room" />
            <asp:Label
cssClass="lblValue" ID="RoomLabel" runat="server" Text='<%#
Bind("RoomName") %>'></asp:Label><br />

            <asp:Label
cssClass="lblIdentifier" ID="lblPhone" runat="server"
meta:resourcekey="Phone" />
            <asp:Label
cssClass="lblValue" ID="PhoneLabel" runat="server" Text='<%#
Bind("PersonPhone") %>'></asp:Label><br />

            <asp:Label
cssClass="lblIdentifier" ID="lplPhonePrivate" runat="server"
meta:resourcekey="Private" />
            <asp:Label
cssClass="lblValue" ID="PhonePrivateLabel" runat="server" Text='<%#
Bind("PersonPhonePrivate") %>'></asp:Label><br />

            <asp:Label
cssClass="lblIdentifier" ID="lblPhoneMobile" runat="server"
meta:resourcekey="Mobile" />
            <asp:Label
cssClass="lblValue" ID="PhoneMobileLabel" runat="server" Text='<%#
Bind("PersonPhoneMobile") %>'></asp:Label><br />

            <asp:Label
cssClass="lblIdentifier" ID="lblEmail" runat="server"
meta:resourcekey="Email" />
            <asp:Label
cssClass="lblValue" ID="EmailLabel" runat="server" Text='<%#
Bind("PersonEmail") %>'></asp:Label><br />
           
           
<asp:LinkButton cssClass="lnkButton" ID="DeleteButton"
runat="server" CausesValidation="False" CommandName="Delete"
Text="<%$resources:translations,
Delete%>"></asp:LinkButton>
           
<asp:LinkButton cssClass="lnkButton" ID="EditButton" runat="server"
CausesValidation="False" CommandName="Edit"
Text="<%$resources:translations,
Edit%>"></asp:LinkButton>
        </ItemTemplate>
    </asp:FormView>
</asp:Content>


And then once again a totally different question: Is there a way to
post the highlighted aspx or vb code into this forum and keep the
colors? i think I've seen that in some posts but didn't wanna do it
manually.

Thanks once again for trying to help,

Toob

View 1 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved