Stored Procedure:calculating Minus Dependent On Type With Group By

Aug 6, 2004

Hi i am trying to get the following result:


CALCULATE THE CURRENT NUMBER OF SHARES on base of number of shares bought and number of shares sold





so the logic is


int total


if transactiontype is "buy", total = total + amount bought


if transactiontype is sell, total = total-amount sold


plus must be grouped by share





base data are stored in 1 table as


share name transaction type share amount


tesco buy 200


tesco sell 50





sounds rather easy does it not?


well sql syntax must be very foreign to me as i do not manage it


I tried a few options:


1 to write a database function as above and then call it from sproc


but i need to use group by share name or id so it calculates for each share and it will not let me to use function in select with group by


2 i tried to use if within sproc but i get complain incorrect syntax (I use MSDE database accessed via Visual) - I think it suppose to be possible but it throws me out with the most simple if or = is there some special syntax?


3 I created 2 views: 1 view: all sold shares, 2nd view: all bought shares and their bought/sold quantities


as in


select share name, sum(sharequantity)


where transaction = sell


from table


group by share name


and the same for purchases


then I did union of these 2 views with boughtquantity - soldquantity what worked but it only showed me shares which were sold, if share was never sold it was not shown I guess due to union


so I am still stuck!

View 7 Replies


ADVERTISEMENT

Dependent Resultsets In A Stored Procedure

Feb 18, 2003

Hi there,

I'd need to generate multiple recordsets within a MS SQL stored procedure. The thing is these recordsets depend on each previous one (the first one obviously has parameters). How can I make this work? I can't create views with SPs. Thank you very, very much.

Martin

View 4 Replies View Related

How To Find Dependent/Referenced Objects Of A Stored Procedure?

Jan 31, 2007

Hi Frens,

Could anybody tell me how can I find all the database objects that are used in /referenced by/called by/dependent on a given stored procedure? In other words, I am looking for something like a stored procedure or a function that takes as input the name of a stored procedure and outputs all the names of the tables, functions, procedures, cursors and etc. database objects that are used in that procedure. Could you please give me suggestions or possible answers for this?

Thanks a lot for your time.
Regards,
-Ram.

View 11 Replies View Related

Group By Date In Stored Procedure

Sep 12, 2007

I am trying to to a transaction count (per day) running a stored procedure that does a group by date. The problem is that since the date has a time stamp (I assume) it sees each date as a different group even if it's the same day. Is there a way to format the date in the stored procedure so that it sees all of the transactions on the same day as one or is there another way to do this.
Select count(recordid),transactiondatefrom sometable group by transactiondate
Thanks
in advance

View 1 Replies View Related

Bit Type Parameter For Stored Procedure

Apr 19, 2004

I am trying to supply a bit type parameter to a stored procedure. This is used to update a Bit type field in a table. The field is called PDI

The syntax I am trying to use is:

MyStoredProcedure.Parameters.Add(New SqlParameter("@Pdi",SqlDbtype.bit))
MyStoredProcedure.Parameters("@pdi").value = -1

When I do my ExecuteNonQuery I get error 8114

What am I doing wrong?

View 9 Replies View Related

Changing Stored Procedure 'type'

May 25, 2000

Is there any way to change the 'type' of a stored procedure from 'user' to 'system'?

View 1 Replies View Related

Getting Return Type From Stored Procedure

Sep 7, 2006

Hi all,

I am trying to figure out a way to analyze a stored procedure to deduce its output type.

A stored procedure can return values throught one of the following:

1) Using the Return keyword

2) Returning a recordset

3) Throught its Output parameters

4) A combination of 1, 2 or 3

Using the Information_Schema, you can access the SQL code of the stored procedure from, say, VB.Net. From there, I want to know what output type the stored procedure has.

A) for 1), I guess I can parse the code for the 'Return' keyword, but that wouldn't be efficient, for the 'Return' word could be inserted into string values...

B) for 2), it would be difficult to analyze the stored procedure's code to know FOR SURE whether a recordset is returned. You just can't parse for SELECT keywords in complex code...

C) 3) should be easy enough, getting the return parameters types from the Information_Schema.



So, is there an easy way that I missed for achieving this, some object in the .Net Framework that I could use to analyze SQL queries perhaps, or am I doomed to do it the hard way?

Thanks,

-Etienne

View 8 Replies View Related

Stored Procedure Parameter Without Type

May 23, 2006

Hi All !

How i can create a stored procedure like ISNULL ?

I need to a procedure that accepts Int type parameters and Float type ect.



Thanks. DBT.

View 5 Replies View Related

Is It Possible To Capture An OUT Type Parameter From A PL/SQL Stored Procedure?

Dec 19, 2007

When a stored PL/SQL procedure in my Oracle database is called from ASP.NET, is it possible to retrieve the OUT parameter from the PL/SQL procedure?  For example, if I have a simple procedure as below to insert a row into the database.  Ideally I would like it to return back the parameter named NewId to my ASP.NET server.  I'd like to capture this in the VB.NET code. 1 create or replace procedure WriteName(FirstName in varchar2, LastName in varchar2, NewId out pls_integer) is2 3 NameId pls_integer;4 5 begin6 7 select name_seq.nextval into NameId from dual;8 9 insert into all_names(id, first_name, last_name)10 values(NameId, FirstName, LastName);11 12 NewId := NameId;13 14 end WriteName;  1 <asp:SqlDataSource 2 ID="SqlDataSaveName" 3 runat="server" 4 ConnectionString="<%$ ConnectionStrings:ConnectionString %>"5 ProviderName="<%$ ConnectionStrings:ConnectionString.ProviderName %>" 6 SelectCommand="WRITENAME"7 SelectCommandType="StoredProcedure">8 <SelectParameters>9 <asp:ControlParameter ControlID="TextBoxFirstName" Name="FIRSTNAME" PropertyName="Text" Type="String" />10 <asp:ControlParameter ControlID="TextBoxLastName" Name="LASTNAME" PropertyName="text" Type="String" />11 </SelectParameters>12 </asp:SqlDataSource>This is then called in the VB.NET code as below. It is in this section that I would like to capture the PL/SQL OUT parameter NewId returned from Oracle. 1 SqlDataSaveName.Select(DataSourceSelectArguments.Empty) If anybody can help me with the code I need to add to the VB.NET section to capture and then use the returned OUT parameter then I'd be very grateful.

View 2 Replies View Related

Data Type Conversion In Stored Procedure

Aug 2, 2006

Hi,

I have a stored procedure a portion of which looks like this:


IF (CAST (@intMyDate AS datetime)) IN (
SELECT DISTINCT SHOW_END_DATE
FROM PayPerView PP
WHERE PP_Pay_Indicator = 'N' )
BEGIN
--ToDo Here
END


where:
@intMyDate is of type int and is of the form 19991013
SHOW_END_DATE is of type datetime and is of the form 13/10/1999

however when I run the procedure in sql query analyzer as:

EXEC sp_mystoredproc param1, param2

i get the error:


Server: Msg 242, Level 16, State 3, Procedure usp_Summary_Incap, Line 106
The conversion of a char data type to a datetime data type resulted in an out-of-range datetime value.


what is the proper way of doing the conversion from int to datetime in stored procedure?

thank you!

cheers,
g11DB

View 11 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

How To Update Group Of Records In SQL Statement Or Stored Procedure

Dec 5, 2007

I have a query that brings back the data below. I need to divide the BudgetTotal by the Count. Then I need to go to the records that make up those €œgroups€? and enter a Budget value = BudgetTotal/Count.

How could I write this in a stored procedure or a SQL statement if possible?

Thanks.

Kevin


SELECT TOP 100 PERCENT dbo.ReportTable.ProjectNo, dbo.ReportTable.Category, dbo.ReportTable.Type, COUNT(dbo.ReportTable.ProjectNo) AS count,
dbo.ReportTable.Budget, dbo.OracleDownloadBudget.Budget AS Expr1
FROM dbo.ReportTable INNER JOIN
dbo.OracleDownloadBudget ON dbo.ReportTable.Category = dbo.OracleDownloadBudget.Category AND
dbo.ReportTable.ProjectNo = dbo.OracleDownloadBudget.Project AND dbo.ReportTable.Type = dbo.OracleDownloadBudget.Type
GROUP BY dbo.ReportTable.ProjectNo, dbo.ReportTable.ProjectName, dbo.ReportTable.Category, dbo.ReportTable.Type, dbo.ReportTable.Budget, dbo.OracleDownloadBudget.Budget
HAVING (dbo.ReportTable.Budget < 1)
ORDER BY dbo.ReportTable.ProjectNo





ProjectNo

Category

Type

Count

Budget

BudgetTotal


100143

Travel

Travel, Meals, No Report IRS

2

0

300.27


100146

Travel

Travel Costs, Training (all)

1

0

300.27


100164

Supplies & Materials

Supplies, Educational

1

0

300.27


100167

Equipment

Eq NonCapital Desktop Comp

1

0

300.27


100170

Faculty Salaries

FB, Faculty

11

0

300.27


100170

Faculty Salaries

Salary, Faculty, T&R FT

11

0

300.27


100170

Wages

Wages, Student

2

0

300.27


100171

Faculty Salaries

FB, Faculty

19

0

300.27


100171

Faculty Salaries

Salary, Faculty, T&R FT

19

0

300.27


100176

Scholarships & Fellowships

Fell, Assist, Out, Grad

1

0

300.27


100177

Scholarships & Fellowships

Fell, Assist, In, Grad

1

0

300.27


View 5 Replies View Related

EXPERT: Stored Procedure Operand Type Clash

Aug 18, 2006

Im trying to insert a new record into tblMessages...the unique ID generated for MessageID is the value I want to use as a value for the MessageID field when inserting a new record in tblUsersAndMessagesI have the following sp:
-- ================================================
-- Template generated from Template Explorer using:
-- Create Procedure (New Menu).SQL
--
-- Use the Specify Values for Template Parameters
-- command (Ctrl-Shift-M) to fill in the parameter
-- values below.
--
-- This block of comments will not be included in
-- the definition of the procedure.
-- ================================================
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: <Author,,Name>
-- Create date: <Create Date,,>
-- Description: <Description,,>
-- =============================================
CREATE PROCEDURE spNewMessage
@UserIDSender nvarchar(256),
@MessageTitle nvarchar(50),
@MessageContent text,
@MessageType int,
@MessageID uniqueidentifier,
@UserID uniqueidentifier
AS
Begin
Set NoCount on
DECLARE @WhateverID uniqueidentifier
INSERT INTO tblMessages(UserIDSender,MessageTitle,MessageContent,MessageType)
VALUES (@UserIDSender,@MessageTitle,@MessageContent,@MessageType)
Select @WhateverID=@@Identity
INSERT INTO tblUsersAndMessages(MessageID,UserID)
VALUES (@WhateverID,@UserID)
End
GO
And here are my tables:tblUsersAndMessages                                            allow nullsMessageID   uniqueidentifier falseUserID           uniqueidentifier falseNew              bit                  false               *default set to ((1)) 
tblMessages                                               allow nullsMessageID       uniqueidentifier false         *PK default set to (newid())UserIDSender    uniqueidentifier falseMessageTitle       nvarchar(50)     trueMessageContent text                  trueSentDateTime    datetime           false      * default set to (getdate())MessageType       int                  false
Now when I try to add my SP I get this error:Msg 206, Level 16, State 2, Procedure spNewMessage, Line 22Operand type clash: numeric is incompatible with uniqueidentifierWhat can this be?!?

View 4 Replies View Related

Data Type Of Parameter Passing To A Stored Procedure

Feb 25, 2004

Hi,
I pass a paramter of text data type in sql server (which crosspnds Memo data type n Access) to a stored procedure but the problem is that I do not know the crossponding DataTypeEnum to Text data type in SQL Server.

The exact error message that occurs is:

ADODB.Parameters (0x800A0E7C)
Parameter object is improperly defined. Inconsistent or incomplete information was provided.

The error occurs in the following code line:
.parameters.Append cmd.CreateParameter ("@EMedical", advarwchar, adParamInput)

I need to know what to write instead of advarwchar?
Thanks in advance

View 1 Replies View Related

How Do I Change The Type Of A Stored Procedure From User To System?

Aug 11, 2005

I built a database by using a generated script from the originaldatabase. It built the System Store Procedures as User type. How do Ichange them back to System type?

View 4 Replies View Related

Variable Type Errors When Calling Stored Procedure

May 12, 2008

I currently have a stored procedure that is defined as follows:


CREATE PROCEDURE UpdateSyncLog

@TableName char(100),

@LastSyncDateTime datetime,

@ErrorState int OUTPUT


I am using an execute sql task to call this procedure. The connectiontype is ADO .NET and the SQLSourceType is DirectInput. The IsQueryStoredProcedure setting is false, and the following is my SQL Statement I have entered:

exec UpdateSyncLog 'myTestTable', @LastSyncDateTime, @ErrorState

Result set is set to None, as this query returns NO results (i.e. has no select statements in it that returns results).

I have two variables in this SSIS package. CurrentDateTime, and ErrorStateVal. CurrentDateTime is of Data type DateTime, the ErrorStateVal is of type Int32

The parameter mappings are as follows:

Varialbe Name=User::CurrentDateTime, Direction=Input, DateType=DateTime, Parameter Name=@LastSynDateTime, Parameter Size=-1

Variable Name=User::ErrorStateVal, Direction=Output, DateType=Int32, Parameter Name=@ErrorState, Parameter Size=-1

The error I am getting when running this execute sql task is as follows:


Error: 0xC001F009 at AS400 to SQL Full Repopulation Sync: The type of the value being assigned to variable "User::ErrorStateVal" differs from the current variable type. Variables may not change type during execution. Variable types are strict, except for variables of type Object.

Error: 0xC002F210 at Execute SQL Task, Execute SQL Task: Executing the query "exec UpdateSyncLog 'myTestTable', @LastSyncDateTime, @ErrorState" failed with the following error: "The type of the value being assigned to variable "User::ErrorStateVal" differs from the current variable type. Variables may not change type during execution. Variable types are strict, except for variables of type Object.

". Possible failure reasons: Problems with the query, "ResultSet" property not set correctly, parameters not set correctly, or connection not established correctly.

Task failed: Execute SQL Task

This makes no sense to me, both the SSIS variable ErrorStateVal is Int32, as well as the parameter declaration in the Execute SQL task is Int32 with direction of OUTPUT, and my stored procedure definition has @ErrorState as an integer as well.

What gives?

View 2 Replies View Related

Converting Date Data Type In Stored Procedure

Jul 31, 2006

HI Experts...

I am using SQL SERVER 2005 standard edition

I have encountered a problem regarding converting date data type in stored procedure

As i was having problem taking date as input parameter in my stored procedure, so, then  I changed to varchar (16) i.e.

CREATE PROCEDURE sp_CalendarCreate
                                      @StDate VARCHAR(16) ,
                                      @EDate VARCHAR(16),

then I am converting varchar to date with following code

DECLARE @STARTDATE DATETIME
DECLARE @ENDDATE DATETIME

SELECT @STARTDATE = CAST(@STDATE AS DATETIME)
SELECT @ENDDATE = CAST(@EDATE AS DATETIME)

When I try to execute the procedure with following code

execute sp_CalendarCreate @stdate='12-1-06',@edate='20-1-06'

but it gives me following error

Msg 242, Level 16, State 3, Procedure sp_CalendarCreate, Line 45
The conversion of a char data type to a datetime data type resulted in an out-of-range datetime value.

Can any one tell me the  solution of that problem (at ur earliest)

regards,

Anas

View 5 Replies View Related

Reporting Services :: Calculating Difference Between Columns Within Column Group

Jun 15, 2015

Given the attached report, is there an easy way of calculating the difference between the Today and QTR Start column? Because of the Account Group, the report looks like the sample shown on the second image.

Sample report:

View 4 Replies View Related

Convert Data File Type From Unix To Pc Using Stored Procedure?

Jul 14, 2006

Hi, I have a script written in ASP to load data file (.csv) to ms sql. In the script, I have a portion of script looks like taht :
.....
Do While NOT oInFile.AtEndOfStream  oOutFile.WriteLine Replace(oInFile.Readline, chr(13), vbcrlf)Loop
.....
After that, I will use a BULK INSERT to input data to ms sql.
I am wondering how do I convert each row (data) to vbcrlf in Stored Procedure? Coz' I did not compose the convertion part, and I got no error when running BULK INSERT, but no rows are inserted :( HELP!!!!
I guess it's because the file is not being converted into a correct format??
 

View 1 Replies View Related

How To Deal With Image Data Type Within Stored Procedure When Using SQL2000?

Dec 5, 2007

Hi,
Does anyone know how to deal with image data type within stored procedure when using SQL2000?
I have a table and there is an image data type column. In this table I need to make a copy of one row within a table through a SP /it means to retrieve the whole row within SP,  change another columns data (but, that the image is not modified) / and save the modified row back to the same table.
Problem is, that within SP is not alowed to use local varaibles of image data type. Does anyone know a solution for this? Please.
Thank you.

View 1 Replies View Related

User Defined Data Type Used In Stored Procedure Parameters

Jul 23, 2005

I have several stored procedures with parameters that are defined withuser defined data types. The time it takes to run the procedures cantake 10 - 50 seconds depending on the procedure.If I change the parameter data types to the actual data type such asvarchar(10), etc., the stored procedure takes less that a second toreturn records. The user defined types are mostly varchar, but someothers such as int. They are all input type parameters.Any ideas on why the stored procedure would run much faster if notusing user defined types?Using SQL Server 2000.Thanks,DW

View 13 Replies View Related

Output Parameter With Text Data Type In Stored Procedure

Jul 20, 2005

How can I make a stored procedure which has a output parameter withtext data type? My procedure is:CREATE PROCEDURE try@outPrm text OutputASselect @outPrm =(select field1 from databaseName Wherefield2='12345')GOHere field1 is text data type.Thanks

View 1 Replies View Related

.NET Framework :: CLR Stored Procedure With Table Data Type Parameter

May 27, 2015

I want to create a CLR Stored Procedure with a Table User Defined Type like this short example in SQL:

CREATE TYPE [dbo].[TypeTable] AS TABLE
(
[Id] [integer] NOT NULL,
[Value] [sysname] NOT NULL,
PRIMARY KEY CLUSTERED

[Code] ....

I found some example in this link : CLR UDT

But I can't figure how to do the same with a User Defined Type Table.

View 5 Replies View Related

How To Conditionally Or Programmatically Run A Stored Procedure With Command Type Set To Storedproc?

May 21, 2008

I'm using SQL RS 2005 and have a report where we want the report to run a different stored procedure depending on if a condition is true. I've set my 'command type' to stored proc and can type in the name of a stored procedure. If I type in just one stored procedure's name, it runs fine. But if I try to use a =IIF(check condition, if true run stored proc 1, if false run storedproc 2) then the exclamation (run) button is greyed out. Does anyone know how I can do this? Thanks.

View 3 Replies View Related

How Can I Change The Data Type Of The Parameter For The Deployed Stored Procedure ??

Jan 11, 2006

Hi
 
I have Try to Create Stored Procedure in C# with the following structure
 
[Microsoft.SqlServer.Server.SqlProcedure]
public static void sp_AddImage(Guid ImageID, string ImageFileName, byte[] Image)
{
       
}
 
But  when I try to deploy that SP to SQL Server Express  , The SP Parameters become in the following Stature
 
@ImageID uniqueidentifier
@ImageFileName nvarchar(4000)
@Image varbinary(8000)
 
But I don€™t want that Data types .. I want it to be in the following format
 
@ImageID uniqueidentifier
@ImageFileName nText
@Image Image
 
 
How Can I Control the data type for each parameter ??
Or
How Can I Change the data type of the parameter for the Deployed Stored Procedure ??
Or
How Can I defined the new Data type ??
 
Or
 
What's the solution to this problem ??
 
Note : I get Error when I try to use Alert Statement to change the parameter Data type for the SP
 
ALTER PROCEDURE [dbo].[sp_AddImage]
      @ImageID [uniqueidentifier],
      @ImageFileName nText,
      @Image Image
WITH EXECUTE AS CALLER
AS
EXTERNAL NAME [DatabaseAndImages].[StoredProcedures].[sp_AddImage]
GO
 
And thanks with my best regarding
Fraas

View 7 Replies View Related

Syntax To Pass A Parameter Of Type Nvarchar(max) To Stored Procedure

Dec 26, 2007

I have a stored procedure that contains a paramteter of type nvarchar(max). What is the syntax to pass this parameter to the sp from a VB.Net application. Specifically, I need to know what to put in the 3rd parameter below:

cmd.Parameters.Add("@Name", SqlDbType.NVarChar, , Name)

View 1 Replies View Related

Error Converting Data Type Varchar To Numeric In Stored Procedure

Aug 28, 2012

Here's the SP

Code:
USE [byrndb]
GO
/****** Object: StoredProcedure [dbo].[sp_GetLikeJobsByJobNumber] Script Date: 08/28/2012 15:17:28 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON

[Code] ....

Why when I run

Code:
USE [byrndb]
GO
DECLARE@return_value int
EXEC@return_value = [dbo].[sp_GetLikeJobsByJobNumber]
@number = N'23913'
SELECT'Return Value' = @return_value
GO

Am I getting an "Msg 8114, Level 16, State 5, Procedure sp_GetLikeJobsByJobNumber, Line 16

Error converting data type varchar to numeric." error? Line 16 is "@number varchar = null"

View 5 Replies View Related

Input Parameter Exceeds The Limit Of The Data Type's Length In Stored Procedure

Sep 4, 2007



Hi guys, is there any way to solve my problem as title ? Assuming my stored proc is written as below :

CREATE PROC TEST
@A VARCHAR(8000) = '1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,...,5000'

AS
BEGIN

DECLARE @B nvarchar(MAX);
SET @B = 'SELECT * FROM C WHERE ID IN ( ' + @A + ')'

EXECUTE sp_executesql @B
END
GO

View 2 Replies View Related

Create A Compatible Function That Can Invoke A Stored Procedure Without Writing The ParameterName And Remembing The Type And Size....

May 30, 2008

suppose,the type of the stored procedure's paramters is varchar .I hate to add parameterNames and types.If i can read the string of the stored procedure the get the paramterNames by operating text?
public void storeOperate(string stringParameter,string name)    {        string[] strs=stringParameter.Split('&');        SqlConnection conn = new SqlConnection(getConnectionString.getconnectionString());        SqlCommand cmd=new SqlCommand(name,conn);        cmd.CommandText=name;        cmd.CommandType=CommandType.StoredProcedure;        foreach(string str in strs)        {            cmd.Parameters.Add(".....",SqlDbType........).Value=str;  //my trouble        }        conn.Open();        cmd.ExecuteNonQuery();        conn.Close();        cmd.Dispose();    }

View 2 Replies View Related

How To Declare A Procedure Parameter Type To Match A Referenced Table Colum Type

Dec 14, 2007

I like to define my procedure parameter type to match a referenced table colum type,
similar to PL/SQL "table.column%type" notation.
That way, when the table column is changes, I would not have to change my stored proc.
Any suggestion?

View 1 Replies View Related

Reporting Services :: Calculating Grand Totals From Group Totals

May 9, 2015

I have some data grouped in a table by a certain criteria, and for each group it is computed a subtotal for the group. Of the values from each of the group, I want to create a grand total on the report by adding every subtotal from each group.

Example:
...
....
Group1              Value
                           10
                            20
Sub Total 1:         30

Group2                 Value
                              15
                              25
Sub Total 2:           40

Now, I would like to be able to add subtotal 1 (30) to subtotal 2 (40) and my grand total would be 70. Can I accomplish this task in SSRS?

View 5 Replies View Related

Using Group By For Text Data Type

May 22, 2006

Hi,I have a problem on an old app. This application is a Help Desk, any Computer related problem (Motherboard Burn Out, Software Crash, dll) on my company will be recorded using this Help Desk application.One month ago, some programmer found a bug in this program lead to many duplicate data on database. But too late, This program has entered production stage and used for more than 2 years. This bug only happen at some condition so I found out after 2 years running (when my boss reported there are some duplicate data on "helpDesk" table).The bug is solved but helpDesk table need some "cleaning" operation. Here is structure of that table :helpDesk Table- id (primary key, integer auto increment)- reported_by (varchar 200)- problem_title (varchar 200)- problem_description (text)- date_summited (datetime)well usualy if I want to find some duplicate data I wil type :SELECT     MAX(uid) AS uid, reported_by, problem_title, COUNT(uid) AS total_duplicateFROM         problemsGROUP BY problem_title, problem_description,uidHAVING      (COUNT(uid) > 1)But that query will not work because problem_description data type is "text" which not support "group by" statement.Any other Idea how to locate and cleaning up this duplicate data?thanks

View 2 Replies View Related

Calling A Stored Procedure Inside Another Stored Procedure (or Nested Stored Procedures)

Nov 1, 2007

Hi all - I'm trying to optimized my stored procedures to be a bit easier to maintain, and am sure this is possible, not am very unclear on the syntax to doing this correctly.  For example, I have a simple stored procedure that takes a string as a parameter, and returns its resolved index that corresponds to a record in my database. ie
exec dbo.DeriveStatusID 'Created'
returns an int value as 1
(performed by "SELECT statusID FROM statusList WHERE statusName= 'Created') 
but I also have a second stored procedure that needs to make reference to this procedure first, in order to resolve an id - ie:
exec dbo.AddProduct_Insert 'widget1'
which currently performs:SET @statusID = (SELECT statusID FROM statusList WHERE statusName='Created')INSERT INTO Products (productname, statusID) VALUES (''widget1', @statusID)
I want to simply the insert to perform (in one sproc):
SET @statusID = EXEC deriveStatusID ('Created')INSERT INTO Products (productname, statusID) VALUES (''widget1', @statusID)
This works fine if I call this stored procedure in code first, then pass it to the second stored procedure, but NOT if it is reference in the second stored procedure directly (I end up with an empty value for @statusID in this example).
My actual "Insert" stored procedures are far more complicated, but I am working towards lightening the business logic in my application ( it shouldn't have to pre-vet the data prior to executing a valid insert). 
Hopefully this makes some sense - it doesn't seem right to me that this is impossible, and am fairly sure I'm just missing some simple syntax - can anyone assist?
 

View 1 Replies View Related







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