Ideas Needed For This Sproc

Jan 24, 2008

Hi,

I want to write a sproc whose main table is Order and it inner joins another table called OrderShipTo with a one to many relationship so the way i have written the first query is as follows

 SELECT
o.OrderId,
o.OrderDate,
o.PlanId,
o.CreatedByUserId,
o.Quantity,
o.BillToCompany,
o.BillToContact,
o.BillToAddress,
o.BillToCity,
o.BillToState,
o.BillToZip,
o.BillToEmail,
o.BillToPhone,
o.ShipToIsBillTo,
o.BookTypeId,
o.RequiredDeliveryDate,
o.SpecialInstructions,
o.ApprovedBy,
o.ApprovedByPhone,
o.ApprovedByEmail,
os.ShipToId,
os.ShipTypeId,
os.ShipToCompany,
os.ShipToContact,
os.ShipToAddress,
os.ShipToAddress1,
os.ShipToCity,
os.ShipToState,
os.ShipToZip,
os.ShipToEmail,
os.ShipToPhone,
os.Quantity
FROM
[Order] o
Inner Join OrderShipTo os on o.OrderId = os.OrderId
WHERE
o.OrderId = @OrderId

 So suppose if i give an OrderId of 15 In the OrderShipTo table they may be 3 Or 2 or none entries for this order in the Ordership to Table So if there is 3 entries in the OrderShip i will get 3 rows of data which is correct... But i just want o.Columns to appear once and i want n rows for the os.Columns to appear.

So in Order To acheive i wrote this query DECLARE @OrderId int
SET @OrderId = 311
SELECT
o.OrderId,
o.OrderDate,
o.PlanId,
o.CreatedByUserId,
o.Quantity,
o.BillToCompany,
o.BillToContact,
o.BillToAddress,
o.BillToCity,
o.BillToState,
o.BillToZip,
o.BillToEmail,
o.BillToPhone,
o.ShipToIsBillTo,
o.BookTypeId,
o.RequiredDeliveryDate,
o.SpecialInstructions,
o.ApprovedBy,
o.ApprovedByPhone,
o.ApprovedByEmail
FROM
[Order] o
WHERE
o.OrderId = @OrderId
EXEC usp_OrderShipToLoadByOrderId @OrderId

 

 

But at the end i want all the rows o.Columns + the rows from os.columns... I also tried giving a union of both the tables but that didnt work of type mismatch..

How can i acheive that???

 Regards

Karen

View 5 Replies


ADVERTISEMENT

Ideas Needed For This Problem (table Structure)

Feb 28, 2008

Hi,
  In my database i have some tables and some are Client, ClientUser, Plan and Platform. We have different products that we offer..
The Client table consits of the following
ClientId  ClientName Contact Platform, Address
 1       abc       johnDoe, 1 anywhere street
2   bca doe john NULL street address and so on..
Client User.
UserId ClientId Lastname Firstname Login Password Active
 1        1       doe            John        abc    XXXX   True
 2        1       abc           kjd          ldkf     XXXX   True
3          2       dfdkjf           jdkfjdl   kdll     XXXX true
 
Plan table
PlanId  ClientId userId Planname ....
1           1         1        abc plan name
2           1          2        abc planname
So on and so forth
Platform
PlatformId   Name
 1              ACC
So my question is in the Plan we have different plans from different user and some of them will be of same client but different Platform or products...
So Platform ACC is some kinda extract where the user get some DBF files and imports it.. where as in the other product they are typed in manually. so how do i differentiate between the two products in the Plan table.. I was thinking of considering this approach.
In the User table add a column called PlatformId too so that in my sproc i can differentiate with it.. so does it make sense to add to the Plan table...
any ideas are appreciated..
Regards,
Karen
 

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

Help Needed With This Query (sproc)

Jun 3, 2008

When i try to run this sproc no rows are are returned but if i give PlanId = 898 and PortfolioId = 1913  i should get one row.. This is my sproc
 ALTER PROCEDURE [dbo].[rpt_Custom_AllocationsSub]
(
@PlanId int,
@PortfolioId int
)
AS
SELECT
c.PlanId,
c.PlanName,
pp.PortfolioId,
pp.PortfolioName,
pp.PortfolioDescription,
f.FundId,
p.displayOrder,
case When pf.PlanFundDisplayName IS NULL THEN f.ShortName ELSE pf.PlanFundDisplayName END FundNames,
CAST(p.AllocationPercent AS integer) AS PPF_Percent
FROM
Fund f
INNER JOIN PlanPortfolioFund p
ON f.FundId = p.FundId

INNER JOIN PlanFund pf
on f.FundId = pf.FundId
RIGHT OUTER JOIN [ClientPlan] c
INNER JOIN PlanPortfolio pp ON c.PlanId = pp.PlanId
ON p.PortfolioId = pp.PortfolioId
WHERE
c.PlanId = @PlanId
ANDp.PortfolioId = @PortfolioId
AND pf.PlanId = pp.PlanId
order by p.DisplayOrder
 This is my table structure
ClientPlanId
  PlanId int indentity
PlanFund -- PlanId int, FundId int
PlanPortfolio -- PortfolioId int, PlanId int, PortfolioName varchar , PortfolioDescription varchar
PlanPortfolioFund PortfolioId int, FundId int, AllocationPercent int.
 
any help will be appreciated...
Thanks
Karen

View 2 Replies View Related

Help Needed In Writing This Sproc...

Nov 8, 2007



Hi i am not sure as u which forum to post but.. i wanted to write a stored procedure and i am stuck as to how to get the data.I have written some which i will post it below but i am not sure how should i go ahead.. These are tables...

I have a table called SourceDBF Which has the following Fields...

RowNumber Plan_NUM PART_ID FUND_ID SOURCE_ID OPENINBAL .... ENDINGBAL

1 265 12345678 ABCDE 1 12.23 17.23
2 265 12345678 ABCDE 3 15.45 19.11
3 265 1234986 CFDEV 1 12.46 20.21



So on and so forth so basically the above table willl have PART_ID associated wiht different SOURCE_IDs

And i have another table called PlanDBF WHICH Has the following feilds...

PLAN_NUM PLANNAME SRC1NAME SRC2NAME SRC3NAME ..... SRC15NAME
265 abc Plan Deferral Matching Rollovers SafeHarbor

The relationship between the 2 tables is in PLAN_NUM and if the Source_Id = 1 i need to pull SRC1NAME , If 2 - SRC2Name and so forth..

I want to write a query that will find SOURCE_ID thats been listed in the SourceDBf table but that dont have a SRCNAME to it.. and this is my query to get the corresponding name for the SOURCE_ID and it works fine





Code Block
Select Distinct
@ClientId,
SOURCE_NUM,
(Select CASE s.SOURCE_NUM When 1 Then SRC1NAME
WHEN 2 Then SRC2NAME
WHEN 3 THEN SRC3NAME
WHEN 4 THEN SRC4NAME
WHEN 5 THEN SRC5NAME
WHEN 6 THEN SRC6NAME
WHEN 7 THEN SRC7NAME
WHEN 8 THEN SRC8NAME
WHEN 9 THEN SRC9NAME
WHEN 10 THEN SRC10NAME
WHEN 11 THEN SRC11NAME
WHEN 12 THEN SRC12NAME
WHEN 13 THEN SRC13NAME
WHEN 14 THEN SRC14NAME
WHEN 15 THEN SRC15NAME
END
FROM
PlanDBF p
Where
p.PLAN_NUM = s.PLAN_NUM
) as SourceName
FROM
SourceDBF s



But when i try to join query with this query it doesnt work



Code Block
SELECT
RowNumber,
'Source.Dbf, Plan.Dbf',
'Source Name is missing for Source Number "' + IsNull(RTrim(f.SOURCE_NUM),'Unknown') + '" in Plan.Dbf table.'
FROM
SourceDbf f




I am trying to get SOURCE_ID which do not hae a SRCName.

any help will be appreciated..
Regards,
Karen

View 5 Replies View Related

(Urgent)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



Code Block
ALTER Procedure [dbo].[usp_GetOrdersByOrderDate]
@ClientId nvarchar(max)= NULL,
@StartDate datetime,
@EndDate datetime
AS
Declare @SQLTEXT as nvarchar(max)
if @ClientId is null
Begin
Select
o.[OrderId],
o.[OrderDate],
o.[CreatedByUserId],
c.LoginId,
o.[Quantity],
o.[RequiredDeliveryDate],
cp.PlanId,
cp.ClientPlanId,
cp.ClientId
FROM
[Order] o
Inner Join ClientPlan cp on o.PlanId = cp.PlanId and o.CreatedByUserId = cp.UserId
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,
cp.ClientId
FROM
[Order] o
Inner Join ClientPlan cp on o.PlanId = cp.PlanId and o.CreatedByUserId = cp.UserId
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

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

Any Ideas

Oct 29, 2004

I need for a database to give my users and indication that a renewal has been complete. Basically what happens is every year once a month a report is generated from sql of how many employees need their gaming license renewed the filter is based off of a field called final suit. I need to find a way to let them know through the database that an employee has been renewed. anyone got any ideas??

View 9 Replies View Related

Ideas Anyone

Apr 9, 2007

Hi all
I am fishing for ideas on the following scenario and hope someone can point me in the best direction.

I create a new table and insert data from relevant other tables but i want to set the data in the new table colums to set widths that have leading zeros where applicable.
I.E the new table column is varchar (10) the data going in to the column is coming from another table where the size was varchar (8) but the data was only 2 characters in size so i want to pad it out to the full new varchar (10) with leading zeros if that makes sence.

I am really just trying to get some ideas on the best possible way to do this thanks.

View 2 Replies View Related

Need Ideas

Nov 9, 2007

I have a table with 18,000 records with beg_eff_date since the year 2005. I need to separate the entries based on their daily activity. For example if Beg_eff_date 01/0/2005 then day is "1" if Beg_eff_date is 01/27/2005 then the day is "27".
Repeating the same process until I reach "NOW" present time. Any ideas of how can I do this?

Thank You for all your previous help and the current one!!

View 9 Replies View Related

Any Ideas

Nov 12, 2007

Hi:


I created a Temp Table that hold a collection of records by date.

I need to do create calculation that give me the Total fuel used per day:

c.rcpt_nom_vol -c.rcpt_fuel- c.rcpt_act_vol = Total Fuel used per day.
Then pull the result of this calculation and assign the result to the specific day of the month. For example is the Calculation Result is 4.25 on Feb 12, 2007. Then the record is insert into a Temp Table as 4.25 day #12.

Does anyone has an idea of how to do this? Thanks and Let me know!!!!





Create Table #TP_Daily_Imb(
contract_nbr char (8),
contract_sub_type char (3),
contract_type_code char (3),
current_expirtn_date datetime,
nom_id char(12),
nom_rev_nbr char(2),
beg_eff_date datetime,
rcpt_dlvry_ind float,
rcpt_nom_vol float,
rcpt_fuel float,
rcpt_act_vol float,
end_eff_date_DGC datetime)



SELECT Distinct a.contract_nbr, a.contract_sub_type, a.contract_type_code,a.current_expirtn_date,
b.nom_id, b.nom_rev_nbr,
c.beg_eff_date, c.rcpt_dlvry_ind, c.rcpt_nom_vol, c.rcpt_fuel,c.rcpt_act_vol
from TIES_Gathering.dbo.contract a
Inner Join TIES_Gathering.dbo.NOm b on a.contract_nbr = b.contract_nbr
Inner Join TIES_Gathering.dbo.Nom_vol_detail c on c.Nom_id = b.Nom_id
where (a.contract_sub_type = 'INT') and (a.Contract_type_code ='GTH')
and (DATEADD(mm, DATEDIFF(mm,0,getdate()), 0) < a.current_expirtn_date)
and (c.rcpt_dlvry_ind ='R')

View 9 Replies View Related

Looking For Ideas

Feb 5, 2007

Hi everyone
 
We've got currenlty around 500 dts 2000 in production.
 
In order to know in what ETL processes we have Oracle connections, or FTP tasks or whatever, we did a VB6 app using dtspkg.dll which load all the properties for each DTS into Sql server tables. So that, then you could see from a specific DTS how many connections, Sql Tasks it had and so on..
 
How to accomplish the same with SSIS? I know, doing the same but using .Net, of course, but is there any else approximation? I am little bit concerned when we will have hundreds of them up.
 
Maybe 2005 is offering this feature automatically, I don't know.
 
Thanks in advance for your time/advices/ideas,
 
 
 

View 1 Replies View Related

Ideas

Mar 1, 2008

Am working on an SSIS project and I am not sure how to handle this situation. I have four tables in two completely separate networks {AB} {CD} and I want to populate one of the tables D based on the information from tables A and C with the following scenario I get data from from table A make a lookup transformation to check what did has changed if the data has changed or if there is a new entry in table A get the identity key from table C {they both share a common field} and add the identity key as part of my data inserted in table D




A ----lookup <


data that has changed --- get the identity key from C ---- insert data from table A + identity key into D

View 5 Replies View Related

Looking For Ideas...

Mar 19, 2007

I have a text file that I am importing in a data flow task. Not all of the rows are the same, there are "header" rows that contain a company code.

What I want to do is keep that company code and append that to the row of text that I am writing to a CSV file.

Since you cannot change variables until the post execute, what are my options?

Hope that's clear

Thanks!

BobP

View 3 Replies View Related

Out Of Ideas

May 16, 2008



I have some performance issues which I can not explain; The database it is running on on a dedicated SQL server box with 8 cpu€™s 4 GB memory. Users are connecting with a fat client.

There is hardly on users using it but they are getting long delays. So I kicked of a profiler trace and sp_blocker. I noticed some queries taking over 30 sec to complete in profiler but when I run them in query analyzer they run in under a second.

I check the output from the blocker and there was no blocking over that time period and it was the only processes actually running.

How can it be so slow I have run out of ideas please any ideas would be welcome

Many thanks

View 7 Replies View Related

Looking For Process Ideas

Mar 9, 2007

I'm looking for Ideas on how to handle a Pldege Reminder process. For example; a pledge is made to pay $2400 over the next two years. They will pay $100 per month and each month a reminder will be sent. No real mistery if there is a balance you send a reminder. My problem is how to handle things like what if they want to pay quarterly or annually and how to determine if a payment is really due based on when they paid last, etc... You most likely see what I mean.
If anyone has done this in the past and/or has any ideas and is willing to share I would greatly appreciate any help.
Some stuff that may help you help me better:
tblClient (ClientID)
tblPledge (PledgeID, ClientID, PledegedAmt, PledgeDate,Frequency,NumberYears)
tblPledgePayments (PmtID, PledgeID,PmtAmt,PmtDate)

View 3 Replies View Related

Design Ideas

Jun 2, 2006

I'm new to asp.net. Please help me with some ideas about the design of databases and interface of the web site.
We are a public school district, I want to create a website for families to go on line to update their family and student's demographic information. Basically I put the students' infomation pulled from our student information system software on the web, the parents can log in on line to update it at the beginning of school year. After that, I will create some report and let secretary manually do the update to our student information system.
The demographic infor includes 3 parts,
1. family street address, city, state, zip2 guardian1 primary phones,second phone,  emails. primary phones,second phone3, student date birth, gender. may have multiple students in one family
But how can I track which field parents changed, shall I do it in programming in the web form, or later when I create some kind of reports. For I only want to pull students with the fields that updated and give them to secretary to update manully, and I don't want to generate a full report and let them compare which field is changed and then update, it will take them too much time.
Thanks much in advance

View 3 Replies View Related

DTS To Excel Out Of Ideas!

Apr 11, 2002

I've read thru all the threads here which say basically the same thing, use a drop table & then a create table to clear the spreadsheet. My problem is the process works the first time to create the table in a new Excel file but fails to clear excel after that. The processes drop, create, & pump data all work without fail but the spreadsheet data is appended to. I've used the wizard as well, saved the package and ran it again without success. Anyone ran into this one?

View 1 Replies View Related

Audit Log Ideas

Nov 28, 2000

I have tried to make my basic audit log do more, but i haven't gotten very far;

In my basic audit log, i record this information:

table
type of change
field modified
old value
new value
db user
date/time

This audit records everything, which is great, but it cannot relate information when i go back to analyze the changes; for example, when a "directory" record is added, a user's information may be entered into several different tables, such as:

name (different table)
addresses (different table)
phone numbers (different table)

If one wanted to look up the changes to addresses of a person in the directory based on the person's name, i could not do it with my existing audit log because the addresses would be in a different table than the name table and there is no relating data in the audit log to relate the address changes to a persons name;

What might be a solution? I have tried a few approaches and am at a loss;

Thank you!

--llyal

View 4 Replies View Related

Any Ideas On How To Speed Up This Sp?

Jan 18, 2006

it is working but takes about 3-4 seconds per exec.

CREATE PROCEDURE isp_ap_calc_apt_totals
@p_comp char(2),
@p_vend char(6),
@p_asofdatechar(8)
as

if (@p_asofdate <= '00000000')
begin
set @p_asofdate = '99999999'
end

delete from XAPAPTTOT
where xapt_comp = @p_comp and xapt_vend = @p_vend and xapt_asof_date = @p_asofdate

insert into XAPAPTTOT
select apph_comp, apph_vend, apph_type, apph_id, @p_asofdate,
sum(apph_paymnts),
sum(apph_discts),
sum(apph_adjts),
count(apph_paymnts),
sum(apph_paymnts)+ sum(apph_discts) + sum(apph_adjts) +
b.apt_gross,
0,
max(str(yy,4) + replace(str(mm,2),' ','0') + replace(str(dd,2),' ','0'))
from APPHISTF.a join APTRANF.b on b.apt_comp = a.apph_comp and b.apt_vend = a.apph_vend and b.apt_type = a.apph_type and b.apt_id = a.apph_id
where ((a.apph_comp = @p_comp) and (a.apph_vend = @p_vend) and (a.apph_unpost_dt = 0)
and (str(a.yy,4) + replace(str(a.mm,2),' ','0') + replace(str(a.dd,2),' ','0') <= @p_asofdate))
or ((a.apph_unpost_dt > 0 and a.apph_unpost_dt <= @p_asofdate and b.apt_unposted_fg = 1 and b.apt_comp = @p_comp and b.apt_vend = @p_vend and b.apt_type = a.apph_type and b.apt_id = a.apph_id))
or (((str(a.yy,4) + replace(str(a.mm,2),' ','0') + replace(str(a.dd,2),' ','0') <= @p_asofdate) and a.apph_unpost_dt > @p_asofdate and b.apt_comp = @p_comp and b.apt_vend = @p_vend and b.apt_type = a.apph_type and b.apt_id = a.apph_id))
group by apph_comp, apph_vend, apph_type, apph_id

update XAPAPTTOT
set xapt_last_payck =
(select max(apph_payck) from APPHISTF
where apph_comp = xapt_comp and apph_vend = xapt_vend and apph_type = xapt_type
and apph_id = xapt_id
and str(yy,4) + replace(str(mm,2),' ','0') + replace(str(dd,2),' ','0') = xapt_last_paydt )
where xapt_comp = @p_comp and xapt_vend = @p_vend and xapt_asof_date = @p_asofdate
GO

View 4 Replies View Related

Ideas For Next Version ...

Jan 12, 2007

To Whom It Concerns - MS Product Design - SQL Server Reporting Services:

I've been working with an ASP.NET web based project utilizing SQL Server Reporting Services for a while and have some things that I think need to be addressed in the next version:

1) I finally got security working utilizing the form based authentication of my Web based app and passing that to SSRS through the ReportViewer control. Not that it was easy. From what I see, a lot of people are having problems with this and so I didn't feel like I was alone. That said, instructions on how to do it need to be easier. Ultimately, it would be better if on the ReportViewer control, you could add properties as follows:


* Impersonate SSRS User

* Impersonization Password
2) Maybe I'm missing something, but in the web app the system logs in to different production databases based on the user id. The only way that I can figure out how to make the same reports available to each database (all on the same SQL Server DB) is to copy the reports and change the data source in the copied directory to copy to the new DB in SQL Server. Could ReportViewer contain a property that allows you to override the connection sring?
3) You have the ability to create PDF's. This is a very nice feature. However, I would like to extend the capabilities that you have. I want to be able to embed a PDF inside the report and have it generated in-line with the report. As an example, I have meta data concerning the PDF kept in the database. When the report prints, I want the meta data printed and the full PDF referenced by the meta data to print. I actually posted a message concerning this to find that there is no solution - I've seen that many people have looked at the message indicating that they are interested in the same feature.
4) It would be nice to have additional controls available - panel, calendar , checkbox, checkboxlist, radiobutton, radiobuttonlist and hyperlink in particular.
5) Dashboard widgets that we can use. Your promoting SSRS as a way to build data decision front ends. It would be nice if out of the box SSRS included several widgets that we could use as indicators to metrics being tracked by the system. As it stands, I can do simple bar, line and pie charts and that is about it. No progress bar, no guages. It would be nice to have some sexier graphing components.
All in all, I do like the product. It was a pain to get setup due to the authentication issues, but I do like it.
David L. Collison
Any day above ground is a good day!

View 3 Replies View Related

Performance Degradation - Any Ideas?

Apr 11, 2001

Hi all,

Up until recently one of our SQL 7 databases has been running quite happily. However over the last 2 weeks the users have started to complain about performance levles, operations that would normally take 2-3 seconds now run for about 40 seconds. I have rebuilt all indexes and even ran update statistics althought both the 'Auto create Statistics' and 'Auto update statistics' are turned on. This failed to help so I ended up stopping and starting SQL server but still no luck.

I have run a DBCC SHOWCONTIG and the fragmentation is well within acceptable levels, scan desnity is at 94%. The only other thing I can think of is to reboot the NT server as it has been up for 67 days now. Can anyone else think of anything I might have overlooked?

All replies welcome.

Thanks.

View 2 Replies View Related

Challenging Scenerio - All Are Welcome For Ideas

Feb 7, 2000

I have about 20 remote databases that I need a query/scheduled task to run that generates a .rpt file. That part I can get.

However, I need to get this file to another company (via email or ftp, etc) and make it automated.

For example:

Scheduled task runs twice a month and generates a file that then needs to be emailed to an individual or ftp'd to a ftpsite. Is there a way to do this in SQL 7.0 (or 6.5)?

Thanks for all your help,
Laura

View 2 Replies View Related

Any Ideas On How To Combine Records Into One

Mar 25, 2004

Here is what I have,

select id, name from rss_user

gives me this

r604738 one
r604738 two
r604738 three
r604739 one
r604739 two
r604739 three
r604739 four

I would like to be able to pipe this into a @temp table so it looks like this,

r604738 one,two,three
r604739 one,two,three,four


Any ideas, so far I am drawing a blank.

View 1 Replies View Related

How To Best Approach The Problem - Need Ideas

Mar 18, 2008

SELECT DISTINCT WO_NO, wo_type, wo_status (incomp,compl,open), wo_status_code, wo_create_date, wo_post_date

I need to do a stored proc in sql server 2005 where I have to count the total work orders based on their wo_type + wo_status, i.e. open, compltd, incomplete. For example I may have (wo_types) AB, AC, AD, orders that are in open status. I need to count the total AB_Type, AC_Type, AD_Type then the total of all 3 in another column (as Total Open). I must do this for all wo_status.

I also have to allow the user to be able to enter the date they want. I.e. if they would want to know on 3/17/08 how many orders were opened that day only. I know I have to use a parameter for this but how do i do that?

Should I do separate select statments for each status, multiple tables ?

Also for 'open' wo_status the wo_status_code can change from O to S but it is still considered 'open'. For this wo_status how can I get the most recent status_code for the open order, i.e., I want to count a particular 'open'work order's - most recent status_code in the work order count for a given wo_type -->> the order should only be counted once on any given date entered. So if the status changed from O then S the same at 1pm then 2pm, respectively, then only the 2pm status should be counted. Thanks in advance for your assistance.

View 2 Replies View Related

LDIFDE Csv Import To SQL - Looking For Ideas

Dec 25, 2005

This is a tuffie, but I think I'll learn new techniques in SQL.I wish to put data from MS Active Directory and put it into a table.Specificly I want user information (first name, last name and so forth)and the groups that they belong into a SQL table.LDIFDE is a utility that can create a csv file from an AD server. Thisis a sample output:dn: CN=rob camarda,OU=Corporate,OU=GeographicLocations,DC=strayer,DC=educhangetype: addobjectClass: topobjectClass: personobjectClass: organizationalPersonobjectClass: usercn: rob camardagivenName: robmemberOf: CN=Arlington Admin,OU=Campus Domain Admin,DC=strayer,DC=edumemberOf:CN=Arlington,OU=Arlington,OU=Region2,OU=Geographic Locations,DC=strayer,DC=edumemberOf: CN=RN Report Consumers,OU=Cognos ReportNet,DC=strayer,DC=edusAMAccountName: rob.camardadn: CN=Robert A. Camarda,OU=TechnologyGroup,DC=strayer,DC=educhangetype: addobjectClass: topobjectClass: personobjectClass: organizationalPersonobjectClass: usercn: Robert A. CamardagivenName: RobertmemberOf: CN=Role Regional Director,OU=Roles,DC=strayer,DC=edumemberOf: CN=Role Campus Director,OU=Roles,DC=strayer,DC=edumemberOf: CN=TLSAdmin,OU=Talisma-Users,DC=strayer,DC=edumemberOf: CN=ASPTestReports,OU=Roles,DC=strayer,DC=edumemberOf: CN=IT Report Authors,OU=Roles,DC=strayer,DC=edumemberOf: CN=Developers,OU=TechnologyGroup,DC=strayer,DC=edu memberOf: CN=SQL Backup Admin,OU=TechnologyGroup,DC=strayer,DC=edumemberOf: CN=RN Report MetaData Modelers,OU=CognosReportNet,DC=strayer,DC=edumemberOf:CN=RN Corporate,OU=Corporate,OU=Region2,OU=GeographicLocations,DC=strayer,DC=edumemberOf:CN=Arlington,OU=Arlington,OU=Region2,OU=Geographic Locations,DC=strayer,DC=edumemberOf: CN=RN Administrator System,OU=CognosReportNet,DC=strayer,DC=edumemberOf: CN=RN Administrator Server,OU=CognosReportNet,DC=strayer,DC=edumemberOf: CN=RN Report Authors,OU=Cognos ReportNet,DC=strayer,DC=edumemberOf: CN=Backup Operators,CN=Builtin,DC=strayer,DC=edumemberOf: CN=Domain Admins,CN=Users,DC=strayer,DC=edumemberOf: CN=Administrators,CN=Builtin,DC=strayer,DC=edusAMAccountName: robert.camardaIn this output, each user is separated by a blank line. sAMAccountNameis the user's login ID to ADS. Lines starting with memberOf: shows thepath for each group the user belongs.My thought is to load the text data into a SQL table with the PK beingthe line number. This way the data will stay together. The secondcolumn would be just text, varchar(100).I'd like to end up with a table something likeUSER_ID, GROUP_MEMBERSHIP, GIVENNAMEIn the example of robert.camarda, that user belongs to 7 groups, sothere would be 7 records, one for each group. I think once I have thispart, I can build my final table with PK's an all the good-housekeeping of a SQL Table.Now the part that I have no idea how to solve:How do I convert the data from unfriendly for databases, to something Ican use?1. I know I have a new user when I find dn:2. I know I am done with the user when I get a blank (null) line.3. I know what I want to populate rows with name and the contents onceI find rows starting with memberOf:4. It appears there is a max line length that LDIFDE will export, andstarts a new line. So, it will be necessary to join lines.I would think this is a combo of CURSORS, a do/while loop and otherassorted magic.If someone can help me get started, I would have something to reseachor model from. As of now, im staring and a blank page and not sure howto start. Maybe someone knows of a simular problem that can share theSQL.TIARob

View 1 Replies View Related

Need Help/ideas On Writing A Function (UDF)

May 1, 2008


I would like to write a user defined function that takes as an input a varchar and returns an xml. If the string is valid xml the function would just return it. If the string is not valid xml then the function would encode the value before returning it.

The function would look something like this:





Code Snippet

CREATE FUNCTION dbo.EncodeXMLIfNotValid (

@InputString varchar(max)

)

RETURNS xml

AS

BEGIN

DECLARE @xml xml

BEGIN TRY

SET @xml = CAST(@InputString as xml)

END TRY

BEGIN CATCH

SET @xml = '<![CDATA[' + @InputString + '>]]>'

END CATCH

RETURN( @xml )

END




However, after writting this I figured out that using BEGIN TRY and CATCH is not allowed in a UDF.

Any thoughts or ideas how I could write a function with this behavior?

Bob

View 6 Replies View Related

Any Ideas To Implement This In SSIS?

Feb 26, 2008



Hi,

I need some help regarding SSIS.

I have a table containing a list of source table names to be transferred to destination.I need to pass each and every table name as a variable and based on the name of the variable I need to select data from source and insert into destination.The source and destinations are on 2 different servers.The source tables have different metadata (different column names and data types).Any help how to implement this would be greatly appreciated.


To be more clear I have List table which has below format

TABLE NAME
CUSTOMER
PRODUCT
INVENTORY

Customer , product, inventory are tables names. So my package should first go and collect the table name from LIST table and then transfer the Customer table data from Server A to Server B. This should be repeat untill all the tables listed in LIST table are transferred.

View 3 Replies View Related

Getting A SQL Database Error...any Ideas SQL Experts?

Jun 26, 2007

 I am trying to insert a value into a field in a database named ASPNETDB.MDF.  The table name is "profiles_BasicProperties" and the field name is "UserID".  I get an error when I attempt to do this.  See the code I am using to try to do this below...and then the error that I get which is further down in this post.  Note...both the code and the database are on my laptop.  I can connect to the database just fine using Server Explorer in MS VS 2005.  Thanks in advance for any help anybody can offer...
 Here is the code I am using:
<%@ Page Language="VB" MasterPageFile="~/Master02.master" Title="Create Your Free Account" Debug="true"%><%@ Import Namespace="System.Data.SqlClient" %><%@ Import Namespace="System.Web.Configuration" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder_Main" Runat="Server">
<script runat="server">        Sub CreateUserWizard_CreatedUser(ByVal sender As Object, ByVal e As EventArgs)                Dim CWZ As CreateUserWizard        CWZ = CType(Me.LoginView1.FindControl("CreateUserWizard"), Wizard)
        CreateUserProfile(CWZ.UserName)
    Private Sub CreateUserProfile(ByVal UserName As String)            Dim conString As String = WebConfigurationManager.ConnectionStrings("Main").ConnectionString        Dim con As New SqlConnection(conString)        Dim cmd As New SqlCommand("INSERT profiles_BasicProperties (UserName) VALUES (@UserID)", con)        cmd.Parameters.AddWithValue("@UserID", UserName)        Using con            con.Open()            cmd.ExecuteNonQuery()        End Using            End Sub
</script>
 ...and here is the error and stack trace (the offending Line 49 is in bold):
 Server Error in '/Site_Dev' Application.--------------------------------------------------------------------------------
An attempt to attach an auto-named database for file ~App_DataASPNETDB.MDF failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share. 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: An attempt to attach an auto-named database for file ~App_DataASPNETDB.MDF failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.
Source Error:
Line 47:         cmd.Parameters.AddWithValue("@UserID", UserName)Line 48:         Using conLine 49:             con.Open()Line 50:             cmd.ExecuteNonQuery()Line 51:         End Using 
Source File: C:UsersmdcraggDocumentsWebsiteSite_DevUser_Create.aspx    Line: 49
Stack Trace:
[SqlException (0x80131904): An attempt to attach an auto-named database for file ~App_DataASPNETDB.MDF failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.]   System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection) +736211   System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj) +188   System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) +1959   System.Data.SqlClient.SqlInternalConnectionTds.CompleteLogin(Boolean enlistOK) +33   System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, Boolean ignoreSniOpenTimeout, Int64 timerExpire, SqlConnection owningObject) +237   System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(String host, String newPassword, Boolean redirectedUserInstance, SqlConnection owningObject, SqlConnectionString connectionOptions, Int64 timerStart) +374   System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(SqlConnection owningObject, SqlConnectionString connectionOptions, String newPassword, Boolean redirectedUserInstance) +192   System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, Object providerInfo, String newPassword, SqlConnection owningObject, Boolean redirectedUserInstance) +170   System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection) +359   System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnection owningConnection, DbConnectionPool pool, DbConnectionOptions options) +28   System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject) +424   System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject) +66   System.Data.ProviderBase.DbConnectionPool.GetConnection(DbConnection owningObject) +496   System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection owningConnection) +82   System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory) +105   System.Data.SqlClient.SqlConnection.Open() +111   ASP.user_create_aspx.CreateUserProfile(String UserName) in C:UsersMatthewDocumentsGroup 02 - PoliticoreSite_DevUser_Create.aspx:49   ASP.user_create_aspx.CreateUserWizard_CreatedUser(Object sender, EventArgs e) in C:UsersMatthewDocumentsGroup 02 - PoliticoreSite_DevUser_Create.aspx:30   System.Web.UI.WebControls.CreateUserWizard.OnCreatedUser(EventArgs e) +105   System.Web.UI.WebControls.CreateUserWizard.AttemptCreateUser() +341   System.Web.UI.WebControls.CreateUserWizard.OnNextButtonClick(WizardNavigationEventArgs e) +105   System.Web.UI.WebControls.Wizard.OnBubbleEvent(Object source, EventArgs e) +453   System.Web.UI.WebControls.CreateUserWizard.OnBubbleEvent(Object source, EventArgs e) +149   System.Web.UI.WebControls.WizardChildTable.OnBubbleEvent(Object source, EventArgs args) +17   System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args) +35   System.Web.UI.WebControls.Button.OnCommand(CommandEventArgs e) +115   System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +163   System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +7   System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +11   System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +33   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +5102
 
--------------------------------------------------------------------------------Version Information: Microsoft .NET Framework Version:2.0.50727.312; ASP.NET Version:2.0.50727.312

View 1 Replies View Related

Bulk Insert Problem, Any Ideas?

Nov 11, 2007

Hello, i am trying to get this to work, i made a SP that send internalmessages to x number of users, the users is located in a variable called @To, they are seperated by commas.
INSERT INTO [dbo].[post] (touser, fromuser, subject, body, recived, w, a) (SELECT s.nstr, @From, @Subject, @Message, getdate(), 0, 1 FROM iter_charlist_to_table(@To, DEFAULT) s)
the function iter_charlist_to_table takes the usernames inside of @To and returns a table of usernames, i then want to insert a record for each of these users.
 When i try to run this:
EXEC SendInternalMessageToUsers@From = N'nouser',@To = N'Dirk,piffo,Steve',@Subject = N'Test',@Message = N'This is to test message'I get the following result:
Msg 512, Level 16, State 1, Procedure LaberMail_SendInternalMessageToUsers, Line 36
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
The statement has been terminated.

View 6 Replies View Related

MSDE Install Hangs -- Any Ideas?

Apr 30, 2004

I installed MSDE. Then I changed the name of my machine. Then I uninstalled MSDE, so I could create a new, properly-named instance.

Now, when I try to install, the installer gets about 75% of the way through the "gathering information" stage, and hangs, every time. I have to kill it with Task Manager.

Help! What can I do?

Extra info: I thought maybe the problem was related to Norton AV, so I uninstalled that. While that was uninstalling, the installer announced that there was a "suspended" install of MSDE that needed to be cleared. So I said, yes, clear it. How do I find out if there are other suspended installs in progress?

Thanks...

View 1 Replies View Related







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