Calculating Profit In Sproc

Aug 31, 2004

Hi I am quite struggling to work out how to calculate profit in stored procedure.


The problem is


I have the table:


share name / transaction date/ is it buy or sell / no of shares bought or sold /total cost





I need to calculate how much profit was made on sold shares


The problem is that I need to always assume that you sell shares which were bought first first.


So if I have in chronological order:


tesco buy 50 £200


tesco buy 40 £100


tesco sell 55 £600


profit is


costtobuy of 55 shares: 50 shares at £200 + 5 shares at (£100/40*5 =)£12.50 = £212.50


profit = £600 - £212.5 = £387.50 (too good to be true)








my plan was (if it is too confusing please ignore it and just read the part above)





1 to work out no of shares sold and total cost of sold shares


so


select sum(no of shares) as nosold ,sharename where transaction = sell and sharename= @sharename return noofshares


select sum(totalsold) as totalcostsold , sharename where transaction = sell and sharename = @sharename return totalsold


now i need to loop through buys to work out cost to buy of number of shares sold:





so i need to loop through a table which would have buy transactions only(share name, nobought, totalcost) and check what was the cost to buy of this number of shares:


@nosold(from above table)


@sharename





output totalcosttobuy = 0





if(nobought = nosold) totalcosttobuy = totalcostobuy + totalcost


retrun


else if (nobought>nosold)totalcosttobuy = totalcostobuy + (totalcost/nobought)*nosold


return


else if( nobought<nosold)totalcosttobuy = totalcostobuy + totalcost


nosold = nosold-nobought (go back to beginning of if)


where sharename = @sharename


group by sharename








Well I need this if statement to loop through the rows in the table how can I do that?


Then I can do profit = totalcosttosell - totalcosttobuy

View 4 Replies


ADVERTISEMENT

When Can We Use Profit Chart?

May 3, 2006

Hi, all here,

I have a question about profit chat (with parameters population, fixed cost, individual cost, revenue), so in what kind of cases or scenarios should we use the profit chart?

Thanks a lot  in advance for any guidance.

View 5 Replies View Related

Profit Chart Challange

Sep 2, 2007

I have a population of debitors, and I have been using profit charts in SQL server 2005 to decide which and how many debitors to contact in order to maximize revenue on my debitor portefolio. My question is: Is it possible to set the Revenue Per Individual to a dynamic variable(e.g. a percentage of the debitors debt) instead of a fixed revenue?

Best regards
Capgemini Norway

View 1 Replies View Related

Analysis :: MDX Query For Total Profit

Sep 3, 2015

i am getting error for the mdx query fortotal profitis there any other way to write??????

View 2 Replies View Related

Transact SQL :: How To Get Percentahe Profit Without Error In Zero Divide

Nov 4, 2015

How can I get the value (pr_profit / pr_sales ) * 100,  (cur_profit / cur_sales) * 100 for %profit. When I am giving zero devide error  is coming . How can I give  if pr_profit = 0 then % profit should be zero.

SELECT  
SUM(CASE WHEN invdate >= {d '2015-01-01' } and invdate <={d '2015-11-03' } Then linetotal Else 0 End) as cur_Sales,
SUM(CASE WHEN invdate >={d '2014-01-01' } and invdate <= {d '2014-11-03' } Then linetotal - linecost Else 0 End) as pr_Profit,
SUM(CASE WHEN invdate >= {d '2015-01-01' } and invdate <={d '2015-11-03' } Then linetotal - linecost Else 0 End) as cur_Profit,
SUM(CASE WHEN invdate >= {d '2015-01-01' } and invdate <={d '2015-11-03' } Then linetotal - linecost Else 0 End) -

[code]...

View 5 Replies View Related

SQLDataSource Cntrl - FormView Cntrl - UPD Sproc And Sproc Debugger. I Dare Anyone To Figure This One Out.

Feb 13, 2007

I have attached the results of checking an Update sproc in the Sql database, within VSS, for a misbehaving SqlDataSource control in an asp.net web application, that keeps telling me that I have too many aurguments in my sproc compared to what's defined for parameters in my SQLdatasource control.....
No rows affected.
(0 row(s) returned)
No rows affected.
(0 row(s) returned)
Running [dbo].[sp_UPD_MESample_ACT_Formdata]
( @ME_Rev_Nbr = 570858
, @A1 = No
, @A2 = No
, @A5 = NA
, @A6 = NA
, @A7 = NA
, @SectionA_Comments = none
, @B1 = No
, @B2 = Yes
, @B3 = NA
, @B4 = NA
, @B5 = Yes
, @B6 = No
, @B7 = Yes
, @SectionB_Comments = none
, @EI_1 = N/A
, @EI_2 = N/A
, @UI_1 = N/A
, @UI_2 = N/A
, @HH_1 = N/A
, @HH_2 = N/A
, @SHEL_1 = 363-030
, @SHEL_2 = N/A
, @SUA_1 = N/A, @SUA_2 = N/A
, @Cert_Period = 10/1/06 - 12/31/06
, @CR_Rev_Completed = Y ).
 
No rows affected.
(0 row(s) returned)
@RETURN_VALUE = 0
Finished running [dbo].[sp_UPD_MESample_ACT_Formdata].
The program 'SQL Debugger: T-SQL' has exited with code 0 (0x0).
And yet every time I try to update the record in the formview online... I get
Procedure or function sp_UPD_MESample_ACT_Formdata has too many arguments specified.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.Data.SqlClient.SqlException: Procedure or function sp_UPD_MESample_ACT_Formdata has too many arguments specified.Source Error:




An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
I have gone through the page code with a fine tooth comb as well as the sproc itself. I have tried everything I can think of, including creating a new page and resetting the fields, in case something got broken that I can't see.
Does anyone have any tips or tricks or info that might help me?
 
Thanks,
SMA49

View 3 Replies View Related

EXEC Of A Sproc Within Another Sproc

Apr 23, 2004

I'm sorta new with using stored procedures and I'm at a loss of how to achieve my desired result.

What I am trying to do is retrieve a value from a table before it is updated and then use this original value to update another table. If I execute the first called sproc in query analyzer it does return the value I'm looking for, but I'm not really sure how to capture the returned value. Also, is there a more direct way to do this?

Thanks,
Peggy



Sproc that is called from ASP.NET:

ALTER PROCEDURE BP_UpdateLedgerEntry
(
@EntryLogID int,
@ProjectID int,
@NewCategoryID int,
@Expended decimal(10,2)
)
AS
DECLARE@OldCategoryID int

EXEC @OldCategoryID = BP_GetLedgerCategory @EntryLogID

UPDATE
BP_EntryLog
SET
ProjectID = @ProjectID,
CategoryID = @NewCategoryID,
Expended = @Expended

WHERE
EntryLogID = @EntryLogID

EXEC BP_UpdateCategories @ProjectID, @NewCategoryID, @Expended, @OldCategoryID



Called Sprocs:

*********************************************
BP_GetLedgerCategory
*********************************************
ALTER PROCEDURE BP_GetLedgerCategory
(
@EntryLogID int
)
AS

SELECT CategoryID
FROM BP_EntryLog
WHERE EntryLogID = @EntryLogID

RETURN


*********************************************
BP_UpdateCategories
*********************************************
ALTER PROCEDURE BP_UpdateCategories
(
@ProjectID int,
@NewCategoryID int,
@Expended decimal(10,2),
@OldCategoryID int
)
AS

UPDATE
BP_Categories
SET CatExpended = CatExpended + @Expended
WHERE
ProjectID = @ProjectID
AND
CategoryID = @NewCategoryID


UPDATE
BP_Categories
SET CatExpended = CatExpended - @Expended
WHERE
ProjectID = @ProjectID
AND
CategoryID = @OldCategoryID

View 2 Replies View Related

Exec Sproc In Sproc

Jan 20, 2004

create procedure dbo.GetZipID( @City varchar(30), @State char(2), @Zip5 char(6))
as
DECLARE @CityID integer
declare @StateID integer
declare @ZipID integer
set @ZipID=2
set @Zip5=lTrim(@Zip5)
if @Zip5<>''
SET @ZIPID = (select Min(lngZipCodeID) AS ZipID from ZipCodes where strZipCode=@Zip5)
if @ZipID is null
set @CityID= EXEC GetCityID(@City);
set @StateID= EXEC GetStateID(@State);
insert into ZipCodes(strZipCode,lngStateID,lngCityID) values(@Zip5,@StateID,@CityID)
if @@ERROR = 0
SET @ZIPID = @@Identity
select @ZIPID


GetCityID and GetStateID are two stored procs, how do I execute those two stored procs
in the above stored proc? I mean what is the syntax??

Tks

View 2 Replies View Related

Need Help With An Sproc

Jan 25, 2008

This sproc seems to be way over my head. First off, let's start with the scenario. I have two tables. tblInventory and tblTempCart. Each contain an ItemID and Quantity. I need an sproc that will loop through the rows in tblTempCart and sum the quantity of each ItemID. Then, it needs to update the quantity in tblInventory based on what has been ordered for that ItemID.
What I have tried thus far:
UPDATE      dbo.[4HCamp_tblStoreInventory]SET               Quantity = Quantity -                            (SELECT      SUM(dbo.[4HCamp_tblStoreTempCart].Quantity) AS Quantity                              FROM           dbo.[4HCamp_tblStoreTempCart]                              WHERE       dbo.[4HCamp_tblStoreTempCart].ItemID = dbo.[4HCamp_tblStoreInventory].ItemID)
This works other than if the ItemID doesn't exist in tblTempCart, then it updates the quantity in tblInventory to NULL instead of retaining it's current value. I have no experience with looping in sql so any help will be greatly appreciated.
 Thanks!
Amanda

View 1 Replies View Related

SQL Sproc Help

May 2, 2008

I am trying to design a stored procedure to list out all of the unique software items that have been approved. There are multiple tables involved: CISSoftware, Software, Manufacturers, SoftwareTypes. Despite putting DISTINCT, I am still receiving rows of records where the software title (the title field) is a duplicate. Why is this query not working? Am I overlooking something?
  SELECT DISTINCT CISSoftware.SoftwareID, Software.Title, Manufacturers.ManufacturerID, Manufacturers.ManufacturerName, SoftwareTypes.SoftwareTypeID, SoftwareTypes.Type

FROM CISSoftware, Software, Manufacturers, SoftwareTypes

WHERE CISSoftware.SoftwareID = Software.SoftwareID

AND Software.ManufacturerID = Manufacturers.ManufacturerID

AND Software.SoftwareTypeID = SoftwareTypes.SoftwareTypeID
 

View 4 Replies View Related

Help On Using LIKE In Sproc

Apr 10, 2004

hi all,

I'm trying to learn using sproc in ASP.NET, but ran into problems I couldn't solve. Here're the details

My Table (JournalArticle)
ArticleID - int (PK)
ArticleTitle - varchar
ArticleContent - text

I could run a normal sql string against the table itself in ASP.NET and got the results I expect.
but when using a sproc, i couldn't get anything
The sproc

CREATE PROCEDURE dbo.sp_ArticleSearch(@srch text)
AS SELECT ArticleID, ArticleTitle, ArticleContent
FROM dbo.JournalArticle
WHERE (ArticleAbstract LIKE @srch)
GO

After reading some of the threads here, I experimented by changing ArticleContent and @srch to type varchar, still no luck, it's not returning anything.
I think the problem is when i set the value of @srch (being new at this, I could be seriously wrong though), like this:

prmSearch.ParameterName = "@srch"
prmSearch.SqlDbType = SqlDbType.Text
prmSearch.Value = Request.Form("txtSearch")

My original string looks like this

strSQL = "SELECT * FROM JournalArticle WHERE (ArticleContent LIKE '%" & Request.Form("txtSearch") & "%')"


What am I doing wrong?? Thanks in advance for any help.

View 7 Replies View Related

Sproc Seems To Run Twice Instead Of Once...

Dec 2, 2004

I have tried to mix this around every way I can think of but the procedure inserts two rows instead of one. You will notice that I specify two commands/sprocs. I did that as part of my trying everything. when it was one command/sproc it did the same thing... What am I doing wrong? Please Help! :)

___________________

SPROC:
___________________
CREATE PROCEDURE dbo.sp_addMembershipRole
@INCID Int
AS
declare @literal NVarChar (10)
SET @literal = 'RTRListing'

INSERT INTO dbo.RTR_memberPermissions ([memberID], [Role])
VALUES (@INCID, @literal)
GO
___________________

CODE:
___________________
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Security.Cryptography;
using System.Web.Security;

namespace admin
{
/// <summary>
/// Summary description for createMembership.
/// </summary>
public class createMembership : System.Web.UI.Page
{
protected System.Web.UI.WebControls.RequiredFieldValidator Vusername;
protected System.Web.UI.WebControls.RequiredFieldValidator Vpassword;
protected System.Web.UI.WebControls.RequiredFieldValidator Vretype;
protected System.Web.UI.WebControls.TextBox username;
protected System.Web.UI.WebControls.TextBox password;
protected System.Web.UI.WebControls.TextBox retype;
protected System.Web.UI.WebControls.Label lblError;
protected System.Web.UI.WebControls.Label lblDate;
protected System.Web.UI.WebControls.Button btnAdd;



private void Page_Load(object sender, System.EventArgs e)
{
if(! Page.IsPostBack)
{
string StrContactID = Request.QueryString["CID"].ToString();
Session["CID"]= StrContactID;
}
}

#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: This call is required by the ASP.NET Web Form Designer.
//
InitializeComponent();
base.OnInit(e);
}

/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.btnAdd.Click += new System.EventHandler(this.btnAdd_Click);
this.Load += new System.EventHandler(this.Page_Load);

}
#endregion

public void btnAdd_Click(object sender, System.EventArgs e)
{
int intContactID;
string StrCID = Session["CID"].ToString();
intContactID= Int32.Parse(StrCID);

if(password.Text != retype.Text)
{
lblError.Text = "Retyping of your desired password did not match. Please try again.";
return;
}

string pwdSalt = CreateSalt(5);
string pwd = password.Text;
string pwdHash = CreatePasswordHash(pwd, pwdSalt);
string connStr= "server=****; uid=****; pwd=****; database=****";
string cmdStr= "sp_addMembershipUandP";
string cmd2Str= "sp_addMembershipRole";

SqlConnection CONN = new SqlConnection(connStr);
CONN.Open();

SqlCommand cmd = new SqlCommand(cmdStr, CONN);
cmd.CommandType = CommandType.StoredProcedure;

SqlCommand cmd2= new SqlCommand(cmd2Str, CONN);
cmd2.CommandType = CommandType.StoredProcedure;

SqlParameter param;
param = cmd.Parameters.Add("@username", SqlDbType.NVarChar, 50);
param.Value = username.Text;

param = cmd.Parameters.Add("@password", SqlDbType.NVarChar, 50);
param.Value = pwdHash;

param = cmd.Parameters.Add("@salt", SqlDbType.NVarChar, 50);
param.Value = pwdSalt;

param = cmd.Parameters.Add("@CID", SqlDbType.Int, 4);
param.Value = intContactID;

SqlParameter param2;
param2 = cmd2.Parameters.Add("@INCID", SqlDbType.Int, 4);
param2.Value = intContactID;


cmd.ExecuteNonQuery();
cmd2.ExecuteNonQuery();

CONN.Close();
return;

}
private static string CreateSalt(int size)
{
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
byte[] buff = new byte[size];
rng.GetBytes(buff);
return Convert.ToBase64String(buff);
}
private static string CreatePasswordHash(string pwd, string salt)
{
string saltAndPwd = String.Concat(pwd, salt);
string hashedPwd = FormsAuthentication.HashPasswordForStoringInConfigFile(saltAndPwd, "SHA1");
return hashedPwd;
}
}
}

View 2 Replies View Related

Sproc In A Sproc

Jan 22, 2004

create procedure
GetAddress(@Addr1 varchar(40), @Addr2 varchar(40), @City varchar(30), @State char(2), @Zip5 char(6), @Zip4 smallint)
as
begin
declare @ZipID integer
declare @AddrID integer
set @AddrID=1
if lTrim(@Addr1)<>''


EXEC @ZipID= dbo.GetZipID(@City,@State,@Zip5)


set @AddrID = (select Min(lngAddrID) from dbo.Addrs where lngZipCodeID=@ZipID and Address1=@Addr1 and Address2=@Addr2)
return(@AddrID)
end
GO




In the above sproc I m trying to call another sproc GetZipID . Its giving me an error stating that

"Incorrect syntax near @City. "

Can you help me out? The same syntax works for passing one variable but not for three.

FYI this is the other sproc




CREATE PROCEDURE dbo.GetZipID(@City varchar(30), @State char(2), @Zip5 char(6))
AS
BEGIN
DECLARE @CityID integer
DECLARE @StateID integer
DECLARE @ZipID integer

SET @ZipID=2
set @Zip5=lTrim(@Zip5)
if @Zip5<>''
SET @ZIPID = (select Min(lngZipCodeID) AS ZipID from ZipCodes where strZipCode=@Zip5)
if @ZipID is null

EXEC @CityID = dbo.GetCityID @City
EXEC @StateID = dbo.GetStateID @State

insert into ZipCodes(strZipCode,lngStateID,lngCityID) values(@Zip5,@StateID,@CityID)
if @@ERROR = 0
SET @ZIPID = @@Identity
Return @ZipID
print @ZIPID

END
GO





Thx in advance

View 1 Replies View Related

Sproc This!

May 17, 2004

ha ha ,

havent used sql serv in years, and having trouble wit me sprocet! What devilish deed did i do?

Use Contacts
GO

CREATE PROC MaserIn
@entreddatetime= GETDATE(),
@initialsvarchar(2)=Null,
@Vendorvarchar(50),
@CkNovarchar(20),
@expTypevarchar(15),
@ckDatedatetime,
@ckAmtmoney,
@mIdintOUTPUT

AS

INSERT INTO [Contacts].[dbo].[Master](
[entered], [initials], [Vendor],
[CkNo], [expType], [ckDate], [ckAmt])
VALUES(@entered,
@initials,
@Vendor,
@CkNo,
@expType,
@ckDate,
@ckAmt)

SELECT @mID=@@iDENTITY

View 6 Replies View Related

Is It Possible To Do This In A Sproc

Nov 28, 2007

Hi.

I wanted to know if its possible to do this in a sproc.


if you want to hide the column that has no data, I suggest you to handle these works in your data accessing modular. For example, if you check one of your column is empty, just remove the column in your record set, so the column would not show in the report.


If yes how can i do it..

Any help will be appreciated.

Regards
Karen

View 8 Replies View Related

T-SQL And Calculating A Sum

Sep 26, 2006

I want to sum up a column, but only summing up the top 25 quantites and then I want to subtract the sum of all quantities from the total of the top 25...how would this be done with t-sql?

View 3 Replies View Related

Calculating PK

Jul 2, 2001

SQL7

I am interested in your opinion on the creation of primary keys in a table - simple ones that is. It would be the replacement for an Identity column.

Some say calculate the value off a lookup table, others say use an external object like c++ dll reading/incrementing from a flat file.

Using an identity column reduces portability of the table.

Thoughts ?

Craig

View 2 Replies View Related

Help !!!calculating Age

Nov 15, 2001

Hi,
What the best way to calculate the age given two datetimes.
I tried using the DATEDIFF(yyy,startdate,enddate) but that seems to only compare the year and not look at the specific day.

I am looking for something that would return the following output


birthday= 12/6/1973
EndDate = 11/30/2001
then the age should be 27

If birthday = 12/6/1973
enddate = 12/11/1973
then the age should be 28

thanks in advance
Zoey

View 3 Replies View Related

Calculating RFM

Apr 17, 2007



I'm in the process of developing a Kimball-method CRM data warehouse and I'd like to have Recency, Frequency, Monetary "scores" at the customer level. Am I better off creating these in the relational database and feeding them to SSAS or have SSAS do the aggregations and assign the "scores"?



Also, has anyone located any SSIS transform scripts that would calculated RFM scores? This is probably a pretty easy task in VB.net but I haven't gone down that road yet.



Steve

View 1 Replies View Related

Help Needed With This Sproc

Dec 19, 2007

 
Hi, I am trying to Implement Multi parameter...
 If i give NULL it works fine but if i give '7,4' I get this error message Msg 102, Level 15, State 1, Line 18 Incorrect syntax near '17'.
This is my sproc
  ALTER Procedure [dbo].[usp_GetOrdersByOrderDate]
@ClientId nvarchar(max)= NULL,
@StartDate datetime,
@EndDate datetime
AS
Declare @SQLTEXT nvarchar(max)
If @ClientId IS NULL
Begin
Select
o.OrderId,
o.OrderDate,
o.CreatedByUserId,
c.LoginId,
o.Quantity,
o.RequiredDeliveryDate,
cp.PlanId,
cp.ClientPlanId
FROM
[Order] o
Inner Join ClientPlan cp on o.PlanId = cp.PlanId
Inner Join ClientUser c on o.CreatedByUserId = c.UserId
WHERE
--cp.ClientId = @ClientId
--AND
o.OrderDate BETWEEN @StartDate AND @EndDate
ORDER BY
o.OrderId DESC
END
ELSE
BEGIN
SELECT @SQLTEXT = 'Select
o.OrderId,
o.OrderDate,
o.CreatedByUserId,
c.LoginId,
o.Quantity,
o.RequiredDeliveryDate,
cp.PlanId,
cp.ClientPlanId
FROM
[Order] o
Inner Join ClientPlan cp on o.PlanId = cp.PlanId
Inner Join ClientUser c on o.CreatedByUserId = c.UserId
WHERE
cp.ClientId in (' + @ClientId + ')
AND
o.OrderDate BETWEEN ' + Convert(varchar,@StartDate) + ' AND ' + convert(varchar, @EndDate) + '
ORDER BY
o.OrderId DESC'
execute (@SQLTEXT)

END 
any help will be appreciated.
Regards
Karen

View 4 Replies View Related

SPROC To Select Top N

Jul 5, 2004

hi all

i need to design a SPROC which will return me top n rows from a table.

like GetTopN 4, will give me top 4 tuples


/**
GetTopN
To list top n rows
Date - 05 July 2004
Yogesh Jangam
*/

IF EXISTS (SELECT name FROM sysobjects
WHERE name = 'GetTopN' AND type = 'P')
DROP PROCEDURE GetTopN
GO

/************************ Actual SP Code *********************************/
Create procedure GetTopN (@intN int)
AS
BEGIN
SET NOCOUNT ON
declare

SELECT TOP @intN from Employee -- this part i am not able to write
end


is there a answer?
Thanks

View 2 Replies View Related

When A Sproc Or Table Was Last Used

Sep 21, 2005

How can I determine when a sproc or table was last used?
I suspect that I have many obsolete tables and sprocs in my database but how can I find out for sure??
Thanks,
DL

View 5 Replies View Related

MSSQL SPROC And VB6

May 14, 2006

I wrote the following SPROC and it works the first time i run it. But if I attempt to run it again I get the following T-SQL Error: "There is not enough memory to complete the task. Close down some operations and try again". Then the app closes. Any ideas?

Here is my complete code:


USE IADATA
IF EXISTS (select * from syscomments where id = object_id ('TestSP'))
DROP PROCEDURE TestSP

GO
CREATE PROCEDURE TestSP
/*Declare Variables*/
@ListStr varchar(100) /*Hold Delimited String*/
AS
Set NoCount On
DECLARE@ListTbl Table (InvUnit varchar(50)) /*Creates Temp Table*/
DECLARE@CP int /*Len of String */
DECLARE @SV varchar(50) /*Holds Result */

While @ListStr<>''
Begin
Set @CP=CharIndex(',',@ListStr) /*Sets length of words - Instr */
If @CP<>0
Begin
Set @SV=Cast(Left(@ListStr,@CP-1) as varchar) /*Copies Portion of String*/
Set @ListStr=Right(@ListStr,Len(@ListStr)-@CP) /*Sets up next portion of string*/
End
Else
Begin
Set @SV=Cast(@ListStr as varchar)
Set @ListStr=''
End
Insert into @ListTbl Values (@SV) /*Inserts variable into Temp Table*/
End

Select InvUnit From @ListTbl LT
INNER Join dbo.Incidents ST on ST.Inv_Unit=LT.InvUnit

and my VB6 Code:


Dim adoConn As ADODB.Connection
Dim adoCmd As ADODB.Command
Dim adoRS As ADODB.Recordset
Dim strLegend As String
Dim strData As String

Set adoConn = New ADODB.Connection
adoConn.Open connString

Set adoRS = New ADODB.Recordset
Set adoCmd = New ADODB.Command

With adoCmd
Set .ActiveConnection = adoConn
.CommandText = "TestSP"
.CommandType = adCmdStoredProc
.Parameters.Append .CreateParameter("ListStr", adVarChar, adParamInput, 100)
.Parameters("ListStr").Value = "Unit 41,Unit 32,Unit 34,Unit 54"

Set adoRS = .Execute

Do While Not adoRS.EOF
Debug.Print adoRS.Fields(0).Value
adoRS.MoveNext
Loop

End With

Set adoCmd = Nothing
adoRS.Close
Set adoRS = Nothing
Set adoCmd = Nothing
adoConn.Close
Set adoConn = Nothing

End Sub

Any ideas?

Thanks

View 2 Replies View Related

Newbie - Is This A Job For A Sproc?

Sep 23, 2006

I'm optimizing an Access mdb to run in front of a SS 2005 database. My approach is to move as much of the processing as possible out of Access and in to SQL Server.

I have a report uses an Access query as it's source. One field in that report is generated via a series of 4 or 5 sub-queries that are finally joined in to the report's source query.

I have enough knowhow to turn each individual Access query into a veiw inside SQL server, but I'm wondering if this wouldn't be better accomplished using a stored procedure?

Essentially, I'd need the sproc to open up a set of 50-60 records, loop through them until it finds the first record with certain criteria, then return a certain value as it's result. Finally, I need that vallue to be joined to a view that I will point to as the source for my report in Access.

Is it possible to do this with a sproc? Is this the right way to use a sproc?

View 9 Replies View Related

Now That Does Not Look Like The Right SQL For A System Sproc....

Mar 11, 2008

Hi SQLersI'm in an unusual position of using a SQL box I'm not an admin of. To make it worse, it is SQL 2k. I haven't used this in anger for over a year. I don't even have the 2k tools installed and I'm just using SSMS.sp_adduser ain't working. I've nosed around in master and the reason why is somebody, for some reason, has created a sproc called (you guessed it) master.dbo.sp_adduser.I can't poke around as I would like and I don't have a 2k instance to bugger about with. Correct me if I am wrong but if there is some user defined master.dbo.sp_adduser sproc then there can't be a system sproc to add users? CREATE USER is SQL 2k5 too right? Users do get created by EM by the team managing the box so what command does this use? Anyone know or (flutters eyelashes) fancy running a profiler trace on EM to see?I want to convert my SQL 2k5 security objects script for SQL 2k. I can create the objects in SSMS so not critical."Overriding" system sprocs is not something I would ever do and I have no equivalent testing environment so any help highly appreciatedCheers

View 12 Replies View Related

Sproc In A Function

Jan 20, 2004

CREATE proc dbo.sp_address ( @Abbr char(2) )
as
DECLARE @StateID int
SET @Abbr = UPPER(ISNULL( @Abbr, '' ))
SET @StateID = ( SELECT MIN(lngStateID) FROM dbo.States where strAbbr = @Abbr )
set @StateID=53
IF ( @StateID is null )
INSERT into dbo.States( strAbbr, strName ) VALUES( @Abbr, @Abbr )
if @@ERROR = 0
SET @StateID = @@Identity
return(@StateID)
GO


Can I execute the above stored procedure in a function like this:

create function
sf_GetStateID( @Abbr char(2))
returns integer
begin
declare @StateID int
exec sp_address
return(@StateID)
end

I just want to cross check.

Tks

View 1 Replies View Related

Insert In A Sproc

Jan 23, 2004

I am trying to insert a value with Insert statement in a sproc

create procedure AddNewPersonsFromALSHeadr
as
begin

insert into dbo.Persons(lngSSN,
strNamePrefix,
strFirstName,
lngHomeID,
lngMailID)

select lngFedTaxID,
strNamePrefix,
strFirstName,

exec @HomeId = GetAddress H.strAddress1,strAddress2,H.strCity,H.strState,H.s trZip,H.intZip4,
@HomeId


from dbo.ALSHeadr H


end
go


The probl is while inserting the fourth column values I have to execute a sproc
"GetAddress" and take the value and insert it in "lngHomeID" and the the same value in
"lngMailID". I tried all possible ways for the syntax but 'm getting the error
incorrect sytanx near exec and also syntax error near " . " at H.strAddress1 etc......


FYI this is the sproc GetAddress(I omitted few lines in this sproc)


CREATE procedure dbo.GetAddress(@Addr1 varchar(40), @Addr2 varchar(40), @City varchar(30), @State char(2), @Zip5 char(6), @Zip4 smallint)
as
begin
------------------------------------------
------------------------------------------
--------------------------------------
EXEC @ZipID= dbo.GetZipID @City,@State,@Zip5
return(@AddrID)
print (@AddrID)
end
GO



Tks

View 3 Replies View Related

SPROC PARAMETERS

May 20, 2008

Hi ALL,

wondering if anybody can help me, i've writen a stored procedure to query my database, i want to be able to added a wildcard into a parameter incase i don't want to use it.

(don't laugh at my efforts!!!!:))
i've tried

IF @<PARAM> = NULL
@<PARAM> = LIKE %

I sure this is a simple thing to add basically i need to replace a null with everything!!

can anybody help?

View 3 Replies View Related

Master SPROC Used On Different DBs

Oct 30, 2007

I'm trying to create a stored procedure on my master database that I can query other databases. The reason behind putting it on the master db is so I will have one place to modify the stored procedure instead of potentially a hundred different databases. I am trying to create a stored procedure like the one below, but it seems to not like it and I get the error below. Any suggestions are appreciated.

DECLARE @uName AS nvarchar(30), @dbName as nvarchar(5)
SET @uName='TU'
SET @dbName = '00000'
DELETE FROM [DASHDB].[dbo].users WHERE Username=@uName
EXECUTE('USE ['+@dbName+']')
DELETE FROM DashboardBranches WHERE Username=@uName
DELETE FROM MyDashboardSettings WHERE Username=@uName
DELETE FROM MyFavorites WHERE Username=@uName
DELETE FROM MyModules WHERE Username=@uName
DELETE FROM MyStocks WHERE Username=@uName
DELETE FROM BoardPackage WHERE PackageID IN (SELECT ID FROM BPackages WHERE Username=@uName)
DELETE FROM BPackages WHERE Username=@uName



ERROR:
Msg 208, Level 16, State 1, Line 6
Invalid object name 'DashboardBranches'.


Thanks,
Josh

View 4 Replies View Related

Can't Get SProc To Work

Aug 16, 2005

HiI can't seem to get this procedure to work correctly. Here's my code:DECLARE @PropertyDetails nvarchar (6)Select @PropertyDescription = PropertyDescription from Property whereApplicationID = @applicationidIf @PropertyDescription is not null or @PropertyDescription <> ''BeginIf (select isnumeric(PropertyDescription) from Property where ApplicationID =@applicationid) = 1INSERT INTO #errors VALUES (1410,@ApplicationID, 0, 'Y')ELSEINSERT INTO #errors values (1410, @ApplicationID, 0, 'N')EndI am trying to bring up an error advising users not to capture alphabets in afield called Property Description.I need to bring up the error from the #ERRORS table with the rule number 1410.My Syntax checks successful, but my error does not come up for the users. AmI missing something?Thanks for any help at all, guys.Driesen Pillay--Message posted via SQLMonster.comhttp://www.sqlmonster.com/Uwe/Forum...eneral/200508/1

View 5 Replies View Related

Trouble With SPROC

Oct 1, 2005

Hi guysI having trouble with this sproc. I get the following error when testing:Server: Msg 245, Level 16, State 1, Procedure UTL_CompletenessCheckLoan, Line231Syntax error converting the varchar value 'danwet w125 ' to a column of datatype int.I have declared @Sellername as Varchar. Please can someone tell me what I'mdoing wrong? All it needs to do is return the 'Y' value if there are numericsin the sellername.declare @sellername varchar(40),@applicationid INTselect @sellername = sellername from Seller where ApplicationId =@ApplicationIdIf @sellername is not null or @sellername <> ''beginif (select isnumeric(Sellername) from seller where ApplicationId =@ApplicationId) = 1select 'Y'ELSEselect 'N'endThanks for any helpDriesen--Message posted via SQLMonster.comhttp://www.sqlmonster.com/Uwe/Forum...eneral/200509/1

View 4 Replies View Related

How To Quit An Sproc

Jun 7, 2007

HiI am doing a check and on failing, i have a raiseerror command.I was assuming, once proc reaches raiseerror, it would stop the proc,but i see that the proc gives me an error message, but continues torun thru all the rest of the steps after raiseerror.how do i make the proc quit after reading raiseerror, only thrulabels ?IF @CheckIFFileHasOnlyOneOutputType 1BEGINRAISERROR ('Process Stopped. Input xls file is invalid, as it has morethan one output type specified in the OutputType Column', 16, 1)END--more proc steps are here ...Thanks in advance :RS

View 1 Replies View Related

Tidying Up Of Sproc

Jul 20, 2005

HiI've written this sproc. Can any one suggest any optimisations to themain query and its sub-queries please? Truncated DDL afterCREATE PROCEDURE dbo.spGetUnbilledInfoByClient(@ClientID varchar(5),@Sort int = 0,@Dir int = 0) ASSET NOCOUNT ON-- The Main QuerySELECT mmatter, mdesc1, tkfirst + ' ' + tklast AS Contact,CONVERT(varchar(10), mopendt, 103) As [Date], CONVERT(DECIMAL(18,2),tTime.Cost) AS COST, tTime.Hours, tDisbursements.DisbursementsFROM matterINNER JOIN timekeep ON mbillaty = timekeep.tkinitlEFT JOIN (SELECT cmatter, SUM(Disbursements) AS Disbursements FROM (SELECT dbo.cost.cmatter,CASE WHEN dbo.cost.cauth = 'SO' OR dbo.cost.cauth = 'CF'THEN dbo.cost.cbillamt * 1.175ELSEdbo.cost.cbillamtEND AS DisbursementsFROM dbo.costWHERE (dbo.cost.cstatus = 'b') AND (dbo.cost.cinvoice IS NULL) AND(LEFT(dbo.cost.cmatter, 5) = @ClientID)) AS costsGROUP BY cmatter) AS tDisbursementsON dbo.matter.mmatter = tDisbursements.cmatterINNER JOIN(SELECT dbo.timecard.tmatter, SUM(dbo.timecard.tbillhrs) AS Hours,SUM(dbo.timecard.tbilldol) AS CostFROM dbo.timecard JOIN dbo.batch ON dbo.timecard.tbatch =dbo.batch.bbatchWHERE (dbo.timecard.tinvoice IS NULL)AND (dbo.timecard.tstatus = 'b')AND (LEFT(dbo.timecard.tmatter, 5) = @ClientID)AND (dbo.timecard.tbilldt IS NULL)AND ( NOT dbo.batch.bfindt IS NULL)GROUP BY tmatter) AS tTimeON dbo.matter.mmatter = tTime.tmatter--Sort (see http://www.sqlteam.com/forums/topic...942&whichpage=3)ORDER BYCASE -- numeric fieldsWHEN @Sort = 4 AND @Dir = 0THEN tTime.CostWHEN @Sort = 5 AND @Dir = 0THEN tTime.HoursWHEN @Sort = 6 AND @Dir = 0THEN tDisbursements.DisbursementsEND DESC,CASE -- datetimeWHEN @Sort = 0 AND @Dir = 0THEN mopendtWHEN @Sort = 3 AND @Dir = 0THEN mopendtEND DESC,CASE -- character fieldsWHEN @Sort = 1 AND @Dir = 0THEN mdesc1WHEN @Sort = 2 AND @Dir = 0THEN tkfirst + ' ' + tklastEND DESC,-- ASCCASE -- numeric fieldsWHEN @Sort = 4 AND @Dir = 1THEN tTime.CostWHEN @Sort = 5 AND @Dir = 1THEN tTime.HoursWHEN @Sort = 6 AND @Dir = 1THEN tDisbursements.DisbursementsEND ASC,CASE -- datetimeWHEN @Sort = 0 AND @Dir = 1THEN mopendtWHEN @Sort = 3 AND @Dir = 1THEN mopendtEND ASC,CASE -- character fieldsWHEN @Sort = 1 AND @Dir = 1THEN mdesc1WHEN @Sort = 2 AND @Dir = 1THEN tkfirst + ' ' + tklastEND ASCGOCREATE TABLE [matter] ([mname] [varchar] (24) COLLATE Latin1_General_CI_AS NULL ,[mmatter] [varchar] (15) COLLATE Latin1_General_CI_AS NULL ,[mrtcode] [smallint] NULL ,[mdept] [varchar] (10) COLLATE Latin1_General_CI_AS NULL ,[mopendt] [datetime] NULL ,[mbillaty] [varchar] (8) COLLATE Latin1_General_CI_AS NULL ,[mdesc1] [varchar] (48) COLLATE Latin1_General_CI_AS NULL) ON [PRIMARY]GOCREATE TABLE [cost] ([cindex] [int] IDENTITY (1, 1) NOT NULL ,[cmatter] [varchar] (15) COLLATE Latin1_General_CI_AS NULL ,[camount] [money] NULL ,[cbilldt] [datetime] NULL ,[cbillamt] [money] NULL ,[cinvoice] [int] NULL ,[ccode] [varchar] (7) COLLATE Latin1_General_CI_AS NULL ,[cbatch] [int] NULL ,[cauth] [varchar] (10) COLLATE Latin1_General_CI_AS NULL) ON [PRIMARY]GOCREATE TABLE [costcode] ([cocode] [varchar] (7) COLLATE Latin1_General_CI_AS NULL ,[codesc1] [varchar] (48) COLLATE Latin1_General_CI_AS NULL) ON [PRIMARY]GOCREATE TABLE [timecard] ([tindex] [int] IDENTITY (1, 1) NOT NULL ,[tmatter] [varchar] (15) COLLATE Latin1_General_CI_AS NULL ,[ttk] [varchar] (8) COLLATE Latin1_General_CI_AS NULL ,[tbilldt] [datetime] NULL ,[tbillhrs] [decimal](16, 2) NULL ,[tbillrt] [decimal](16, 2) NULL ,[tbilldol] [money] NULL ,[tinvoice] [int] NULL ,[tcode] [varchar] (7) COLLATE Latin1_General_CI_AS NULL ,[tbatch] [int] NULL) ON [PRIMARY]GOCREATE TABLE [batch] ([bbatch] [int] IDENTITY (1, 1) NOT NULL ,[btype] [varchar] (2) COLLATE Latin1_General_CI_AS NULL ,[bfindt] [datetime] NULL ,[bop] [varchar] (8) COLLATE Latin1_General_CI_AS NULL ,[bper] [varchar] (4) COLLATE Latin1_General_CI_AS NULL ,[bpflag] [varchar] (1) COLLATE Latin1_General_CI_AS NULL ,[bdopen] [datetime] NULL ,[btothrs] [decimal](12, 2) NULL ,[btotdol] [money] NULL) ON [PRIMARY]GO

View 10 Replies View Related







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