TSQL Strored Procedure
Apr 26, 2006
I am having an issue when trying to pull data from Oracle into a sqlSERVER TABLE. I'm running into an issue because I am using to much temporary space in Oracle because the return set is so large. New to sqlserver, but in Oracle the solution would be to commmit the insert after so many records have been retrieved.
Here's the procedure I wrote I would think I need to add a cursor and a counter which be used to do a commit after so many rows have been retrieved. DOes so one have a procedure I could model mine after?
ALTER PROCEDURE [dbo].[SP_Load_BO]
-- Add the parameters for the stored procedure here
@p1 int = 0,
@p2 int = 0
AS
BEGIN
SET NOCOUNT ON;
INSERT INTO MERCHANT_BACKOFFICE_SQLSERVER
(MONTHYEAR,ALLIANCEID, merchantid,rptservid,scid,tabletype,tablenum,VOLUME, COST, COSTPLUS,DATELOAD)
SELECT convert(DATETIME,PERIOD) as PERIOD,
ALLIANCEID,
merchantid,
rpTSERVID,
scid,
tabletype,
tablenum,
Convert(numeric(10),Count) AS VOLUME,
Convert(numeric(24,6),COST) as COST,
Convert(numeric(24,6),COSTPLUS) as COSTPLUS,
convert(datetime,DATE_LOAD) as DATE_LOAD
from
OPENQUERY(INV,'
SELECT MER.MONTHYEAR AS PERIOD,
MER.ALLIANCEID,
MER.merchantid,
MER.RPTSERVID,
MER.SCID,
MER.TABLETYPE,
MER.TABLENUM,
SUM(MER.VOLUME) AS Count,
SUM(MER.COST) as Cost,
SUM(MER.COSTPLUS) as Costplus,
to_char((last_day(add_months(sysdate,-1))+1),''MM/DD/YYYY'') as DATE_LOAD
FROM
MERCHANT_BACKOFFICE_SERVICE MER
WHERE MER.allianceid <>516
group by MER.MONTHYEAR,
MER.ALLIANCEID,
MER.merchantid,
MER.RPTSERVID,
MER.SCID,
MER.TABLETYPE,
MER.TABLENUM')
END
View 5 Replies
ADVERTISEMENT
Oct 23, 2007
Hi All
I am using SQL server 2005.
I have wriiten the Stored Procedure.
Once I modified anything in the Stored Procedure I use ALTER command and save it.
But I am unable to save the comments with this ALTER command which I write in the beginnign of the Stored Procedure.
I have given the example below.
Also please tell me without using ALTER is there any way to save the stored procedure.
For Ex:
/*************************************************************************************************************************************************************************************
* Procedure : pr_Generate_PaymentApproval_List
* * Called By : PPComponent.PPPayment.GetPaymentApprovalList
* Description : This proc is use to retrieve payment approval info
*/
ALTER PROCEDURE dbo.pr_Generate_PaymentApproval_List (
@ins_id BIGINT, @disti_id BIGINT,
@geo_cd NCHAR(4) )
--
--
Regards
Abdul
View 2 Replies
View Related
Nov 13, 2003
Basically, I have a complex stored procedure that combines two tables and fills a cursor.
I would like to fill another cursor in another stored procedure from the results of this first stored proc, rather than have to type it all in again.
The reason being that I am doing a one time import of some data from two tables into one new table based on some complex linking/querying.
Can I fill a cursor from the output of another stored procedure rather than an inline SELECT statement?
Does the sp I am using have to have cursor as an out parameter?
View 4 Replies
View Related
Dec 20, 2007
Hi...
Am working with asp.net with vb for a MusicProject..
In this I have playlist for particular User..ie User Selects Some Songs and clicks on AddToMyPlayList Button....
Here He can insert those songs into a new playlist or update the earlier..
the StroedProcedure is as follws: 'N' means NewPlayList and 'E' means Existing
***************************************************************************************
CREATE PROCEDURE MUSIC_ADD_PLAYLIST ( @PLAYLIST_NAME VARCHAR(255), @USER_ID VARCHAR(255), @ItemList NVARCHAR(4000), @delimiter CHAR(1), @FOLDERNAME VARCHAR(255) ,@PLAYLISTTYPE CHAR(1)) AS SET NOCOUNT ON
DECLARE @IDENT INT
IF @PLAYLISTTYPE = 'N'
BEGIN INSERT INTO MUSIC_PLAYLIST ( MUSIC_PLAYLIST_NAME, MUSIC_PLAYLIST_USER ) VALUES ( @PLAYLIST_NAME, @USER_ID )
SELECT @IDENT=@@IDENTITY FROM MUSIC_PLAYLIST END IF @PLAYLISTTYPE='E'
BEGIN
SELECT @IDENT=MUSIC_PLAYLIST_ID FROM MUSIC_PLAYLIST WHERE MUSIC_PLAYLIST_USER=@USER_ID AND MUSIC_PLAYLIST_NAME=@PLAYLIST_NAME
END
DECLARE @tempItemList NVARCHAR(4000) SET @tempItemList = @ItemList DECLARE @i INT DECLARE @Item NVARCHAR(4000) SET @tempItemList = REPLACE (@tempItemList, ' ', '') SET @i = CHARINDEX(@delimiter, @tempItemList) WHILE (LEN(@tempItemList) > 0) BEGIN IF @i = 0 SET @Item = @tempItemList ELSE SET @Item = LEFT(@tempItemList, @i - 1) -- INSERT INTO @IDTable(Item) VALUES(@Item)
INSERT INTO MUSIC_SONGSLIST (Music_PlayList_Id,Music_SongName,Music_Song_Location) VALUES (@IDENT,@ITEM,@FOLDERNAME+''+@ITEM) IF @i = 0 SET @tempItemList = '' ELSE SET @tempItemList = RIGHT(@tempItemList, LEN(@tempItemList) - @i) SET @i = CHARINDEX(@delimiter, @tempItemList) END
GO
***************************************************************************************
Here the problem is am not getting the exact result means if i add 6 songs to a playlist it is adding only 4 songs to that particular playlist..
Please help me out
Thanks in Advance,
Madhavi
View 1 Replies
View Related
Jul 20, 2005
Hi,I have stored procedure (MS SQL Server 2000) which operateson around 600 000 rows (SELECT, UPDATE, INSERT)and executes in 5 minutes,when I put it in SQL transaction it slows down to more than 5 hours (!!)I have to admit that it is not problem with data locks (beside thatprocedurenothing else is executed on db),It is not also problem with that exact procedure, other proceduresalso slow down heavily when wrapped by SQL transactionvery very seldom stored procedure within transaction executescomparably long that its copy without transactionI guess it could be MS SQL Server 2000 configuration/tuning problem.Any ideas ?Chris
View 1 Replies
View Related
Jan 3, 2008
Pls tell me the main differences b/w user defined function and stored procedure .
View 2 Replies
View Related
Nov 6, 2007
I am building a stored procedure that changes based on the data that is available to the query. See below.
The query fails on line 24, I have the line highlighted like this.
Can anyone point out any problems with the sql?
------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------
This is the error...
Msg 8114, Level 16, State 5, Procedure sp_SearchCandidatesAdvanced, Line 24
Error converting data type varchar to numeric.
------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------
This is the exec point...
EXEC [dbo].[sp_SearchCandidatesAdvanced]
@LicenseType = 4,
@PositionType = 4,
@BeginAvailableDate = '10/10/2006',
@EndAvailableDate = '10/31/2007',
@EmployerLatitude = 29.346675,
@EmployerLongitude = -89.42251,
@Radius = 50
GO
------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------
This is the STORED PROCEDURE...
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go
ALTER PROCEDURE [dbo].[sp_SearchCandidatesAdvanced]
@LicenseType int = 0,
@PositionType int = 0,
@BeginAvailableDate DATETIME = NULL,
@EndAvailableDate DATETIME = NULL,
@EmployerLatitude DECIMAL(10, 6),
@EmployerLongitude DECIMAL(10, 6),
@Radius INT
AS
SET NOCOUNT ON
DECLARE @v_SQL NVARCHAR(2000)
DECLARE @v_RadiusMath NVARCHAR(1000)
DECLARE @earthRadius DECIMAL(10, 6)
SET @earthRadius = 3963.191
-- SET @EmployerLatitude = 29.346675
-- SET @EmployerLongitude = -89.42251
-- SET @radius = 50
SET @v_RadiusMath = 'ACOS((SIN(PI() * ' + @EmployerLatitude + ' / 180 ) * SIN(PI() * p.CurrentLatitude / 180)) + (COS(PI() * ' + @EmployerLatitude + ' / 180) * COS(PI() * p.CurrentLatitude / 180) * COS(PI()* p.CurrentLongitude / 180 - PI() * ' + @EmployerLongitude + ' / 180))) * ' + @earthRadius
SELECT @v_SQL = 'SELECT p.*, p.CurrentLatitude, p.CurrentLongitude, ' +
'Round(' + @v_RadiusMath + ', 0) AS Distance ' +
'FROM ProfileTable_1 p INNER JOIN CandidateSchedule c on p.UserId = c.UserId ' +
'WHERE ' + @v_RadiusMath + ' <= ' + @Radius
IF @LicenseType <> 0
BEGIN
SELECT @v_SQL = @v_SQL + ' AND LicenseTypeId = ' + @LicenseType
END
IF @PositionType <> 0
BEGIN
SELECT @v_SQL = @v_SQL + ' AND Position = ' + @PositionType
END
IF LEN(@BeginAvailableDate) > 0
BEGIN
SELECT @v_SQL = @v_SQL + ' AND Date BETWEEN ' + @BeginAvailableDate + ' AND ' + @EndAvailableDate
END
--SELECT @v_SQL = @v_SQL + 'ORDER BY CandidateSubscriptionEmployerId DESC, CandidateFavoritesEmployerId DESC, Distance'
PRINT(@v_SQL)
EXEC(@v_SQL)
-----------------------------------------------------------------------------------------------------------------
View 4 Replies
View Related
Jun 11, 2001
I have an insert stored procedure which creates a customer. The customer has a ID which is an autonumber within the SQL server table.
I want to output this value to use this to update another table. How do I output a value of an insert query which i am not passing in as it's an autonumber ??
I am sure someone has come accross this before. Is it a trigger solution ?? Any ideas very welcome.
mark
View 2 Replies
View Related
Feb 23, 2007
I have the following for sql server 2000...
Select b.courseName, a.courseId, count(a.courseId) as [count], avg(convert(INT, a.fldScore)) as [average], count(fldPass) as [passed], count(fldPass) as [failed] From tblTest a inner join tblTest2 b on a.courseId = b.courseId Group by a.courseId, b.courseName
Problem is the [passed] and [failed]
As it is, it's counting all of them.
I need to adjust it so passed will only read where fldPass = 'yes'
and fldPass = 'no' for the passed and failed.
Suggestions?
Thanks,
Zath
View 4 Replies
View Related
Feb 29, 2008
Can i execute a URL in tsql stored procedure.
Waht i want's is to hit a url on some event.
I know i can do it in CLR stored procedure but for that i have to deploy assembly on the server which i want's to avoid.
Is there any way i can hit a url from tsql stored procedure
Kamran Shahid
Sr. Software Engineer(MCSD.Net)
www.netprosys.com
View 8 Replies
View Related
Jan 28, 2008
I have a stored Proc, which takes 30 min for execution. If I execute it twice it runs properly but when i do the same the third time, it gets stuck.. any reasoning for this..
I am using Insert into statements a lot here...
View 3 Replies
View Related
Apr 3, 2008
Well I have a two tables lets say they look like as follows:
Table A
CompanyID
Location
TableB
CompanyID
CompanyName
Date
The CompanyID column has values that look like this:
AAA OR
AAA.BBB OR
AAA.BBB.CCC OR
AAA.BBB.CCC.DDD OR
AAA.BBB.CCC.DDD.EEE OR
AAA.BBB.CCC.DDD.EEE.FFF
each line representing the level of the company.
we can see that CompanyID column exists in both tables. and I would like to find out the CompanyName from table B for each companyID that exists in Table A.
but the tricky part is that for a specific CompanyID in tableA I might not have a exact match.
e.g. in A lets say I have AAA.BBB.CCC.DDD.EEE for CompanyID but in table B i might not have AAA.BBB.CCC.DDD.EEE but instead have AAA.BBB or AAA.BBB.CCC or AAA.
so I have to walk up the tree or these levels to look for a match an get the companyName. the match logic is as such.
If in table A companyID = AAA.BBB.CCC.DDD.EEE then look for same value in B if NOT FOUND then
remove the last level from the companyID value from Table A. so new value of CompanyID = AAA.BBB.CCC.DDD
Now look for this new value AAA.BBB.CCC.DDD in table B. IF NOT FOUND then
remove another level from ComapnyID in table A so new companyID = AAA.BBB.CCC and look for
AAA.BBB.CCC in table B. just going up the tree by chopping off a level till I find a match.
now the question is how to do this in TSQL.... can someone help?
So what I really want to do is to look for a match between A and B based on companyID.
View 2 Replies
View Related
May 19, 2008
I have three coloumn in Salary Table
Emp ID, Emp Salary , Sequence
a1 1000 1
a1 2000 2
a1 2000 3
a2 4000 1
a2 5000 2
a2 5000 3
a2 6000 4
Now I have to calculate the count on salary if the previous salary is different then count +1 else is previous salary same then add +0.
so output be
EmpID and Updation in Salary
a1 = 2 and for a2 =3
Can anyone help me with the query or storeprocedure i can achieve this output counting according to previous data.
View 9 Replies
View Related
Dec 31, 2004
I've got the folloing stored procedure
ALTER PROCEDURE AddUserData
(@login varchar (8),
@password varchar (8),
@fullName varchar (50),
@RoleID Int,
@statusID Int)
AS
if exists
(SELECT login, @errorReturn
FROM tbEmployee
WHERE login = @login)
return 55555
Else
INSERT INTO tbEmployee (login, password, fullname, RoleID, statusId)
VALUES (@login, @password, @fullName, @RoleID, @statusID)
RETURN @@error
the function that calls this stored procedure is this
Public Shared Function InsertUserData(ByVal login As String, ByVal password As String, ByVal fullName As String, ByVal StatusID As Integer, ByVal RoleID As Integer)
' Create the connection object
Dim connection As New SqlConnection(connectionString)
' Create and initilise the command object
Dim command As New SqlCommand("AddUserData", connection)
command.CommandType = CommandType.StoredProcedure
command.Parameters.Add("@password", SqlDbType.VarChar)
command.Parameters("@password").Value = password
command.Parameters.Add("@login", SqlDbType.VarChar)
command.Parameters("@login").Value = login
command.Parameters.Add("@fullName", SqlDbType.VarChar)
command.Parameters("@fullName").Value = fullName
command.Parameters.Add("@roleID", SqlDbType.Int)
command.Parameters("@roleID").Value = RoleID
command.Parameters.Add("@statusID", SqlDbType.Int)
command.Parameters("@statusID").Value = StatusID
' Open the connection
Try
connection.Open()
command.ExecuteNonQuery()
Finally
connection.Close()
End Try
End Function
now I'm trying to get ahold of the return value from the stored procedure so I can output a message to the user in a label control.
e.g the soted procedure checks to see if a user already exists if it does it returns 55555. how can I get ahold of this 55555 and place it in a variable in the function so I can then send it to another error function to display the approperate lable message ??
thanks all
View 3 Replies
View Related
Jul 12, 2004
Does anyone know of an internal procedure to return the timestamp of the last time a storedprocedure or table was modified?
Currently the object only lists the creation timestamp.
View 2 Replies
View Related
Jul 18, 2007
Hi,
Can anyone tell me how to export a batch of stored procedures in MS sql server Management studio?
Thanks.
View 1 Replies
View Related
Oct 16, 2007
Hi ,
I ma using sql server 2005.I have a bunch of statements of sql and i have created a stored procedure for those. When i execute i found that there is lot's of difference between execution time of stored procedure and direct sql in query windows.
can anyone help me to optimize the execution time for stored prcedure even stored prcedure is very simple.
I have used sql server 2000 and i am new in sql server 2005.
View 1 Replies
View Related
Nov 19, 2007
Can anyone please give me the equivalent tsql for sql server 2000 for the following two queries which works fine in sql server 2005
1
-- Full Table Structure
select t.object_id, t.name as 'tablename', c.name as 'columnname', y.name as 'typename', case y.namewhen 'varchar' then convert(varchar, c.max_length)when 'decimal' then convert(varchar, c.precision) + ', ' + convert(varchar, c.scale)else ''end attrib,y.*from sys.tables t, sys.columns c, sys.types ywhere t.object_id = c.object_idand t.name not in ('sysdiagrams')and c.system_type_id = y.system_type_idand c.system_type_id = y.user_type_idorder by t.name, c.column_id
2
-- PK and Index
select t.name as 'tablename', i.name as 'indexname', c.name as 'columnname' , i.is_unique, i.is_primary_key, ic.is_descending_keyfrom sys.indexes i, sys.tables t, sys.index_columns ic, sys.columns cwhere t.object_id = i.object_idand t.object_id = ic.object_idand t.object_id = c.object_idand i.index_id = ic.index_idand c.column_id = ic.column_idand t.name not in ('sysdiagrams')order by t.name, i.index_id, ic.index_column_id
This sql is extracting some sort of the information about the structure of the sql server database[2005]
I need a sql whihc will return the same result for sql server 2000
View 1 Replies
View Related
Aug 9, 2006
Hello Friends, I am not sure if this is the right place to post this question but if not please suggest me when it can be posted.
I have been thinking of writing Stored procs in SQL CLR/ changing all of my Stored Procs to SQL CLR.
Is there any thing that I need to keep in mind about the size of the sotred proc (like calculation intensive) before I do that? I mean can even change a TSQL stored proc which is relatively small Stored Proc, that simply said Select * from Customers to SQL CLR? or the SQL CLR does only useful/makes difference with calculation intensive stored procs and big stored procs?
When I talked to our Architects they said every small sized stored proc can be written using SQL CLR and more over forget about the classic TSQL stored procs and get used to write SQL CLR when ever writing any database related stuff.
And also there are so many articles that discussed about the advantages of SQL CLR over the TSQL but I would appreciate if some one could put few bulletted points why do you think SQL CLR is more powerful.
Please advise.Thanks in advance,-L
View 2 Replies
View Related
Jan 8, 2006
Hi
I am creating some dynamic sql by passing variouse parametrs to my Stored Procedure. One of my Parameters is string has lots of values seperated by a comma to help build an 'IN' statement.
SET @SQL = 'SELECT * FROM areas'SET @p1 = '10,20'If @p1 IS NOT NULLBEGINSET @sSQL = @sSQL + ' WHERE (Areas IN (''' + Replace(@p1,',',''',''') + '''))'END
The above query runs perfecly well in Query Analyser, however when I put it into my ASP.NET application I get an error of "Error converting data type varchar to numeric."
So I think I need to do some sort of casting or Converting but im not sure how to do it. Or do I need to use a INSTRING?
I did manage to work out a method by using the follwoing
SELECT * FROM Areas WHERE PATINDEX('%,' + CAST(ArType AS VARCHAR) + ',%',',' + @p1 + ',') > 0
But I cant seem to convert the above line into coherent dynamic statement. My feeble attempt is below but I keep getting errors
SET @sql = @sql + ' WHERE PATINDEX(''%,'' + CAST(ArType AS VARCHAR) + '',%'','','' + @p1 + '','') > 0'
IM strugging to understand all the '''. My TSQL is pretty basic, any help would be much appreciated
Many thanks in advance
View 1 Replies
View Related
Mar 14, 2001
simple update, I want to update max_seq with max(0rdr_seq) from another table.
how do you?
update h
set max_seq = d.max(ordr_seq)
from h_drug_stage_dup h
join drug_ordr_stage d
on h.patkey = d.patkey and
h.ordr_dtm= d.ordr_dtm and
h.h_drug = d.h_Drug
View 1 Replies
View Related
Jun 5, 2001
Please see below ( in my sub-query I need to say settle_date = post_date +
3 business days )
How would this be done ? Pleas help !!!
declare @PD datetime, @MY_SD datetime
--SELECT @PD = SELECT POST_DATE FROM TRANSACTION_HISTORY
--select @MY_SD = @PD + 3 --T+3
--select @MY_SD = @MY_SD + case datepart(dw, @MY_SD) when 7 then 2 when 1 then 1 else 0 end*/
SELECT
WIRE_ORDER_NUMBER FROM TRANSACTION_HISTORY
WHERE POST_DATE BETWEEN '02/01/2001' AND '02/28/2001' AND
WIRE_ORDER_NUMBER IN
(
SELECT ORDER_NUMBER
FROM TRANSACTION_ARCHIVE WHERE TRANSACTION_ARCHIVE.ORDER_NUMBER = TRANSACTION_HISTORY.WIRE_ORDER_NUMBER
SETTLE_DATE = DATEADD(day, 3, POST_DATE ) case datepart(dw, POST_DATE) when 7 then 2 when 1 then 1 else 0 end))
View 5 Replies
View Related
Oct 1, 2001
Sql Server 7.0
==============
Hi all!
To find out the duplicate entries in a particular column,
I used the following tsql
select pno ,count(pno) from table1 group by pno
having count(pno)>1
But now I have another case where i have to test duplicity as a combination of 3 columns.
ie, for Eg :I have 3 columns with the following values.
colA colB colC
1 2 3===============row 1
1 3 5===============row 2
1 2 3===============row 3
1 4 5===============row 4
8 9 0===============row 5
I want to pick up all the duplicate rows(combo of colA,colB,colC)
duplicate rows here would be row 1 and row 3.
Can somebody give me a clue as to how to achieve this via TSQL.
Any help greatly appreciated.
TIA
Kinnu
View 1 Replies
View Related
Oct 1, 2001
HI,
I am creating a stored procedure where i need to update a table.
I have a field which has year as 2000-2001 i need to remove -2001
and just store it as 2000.I created a Procedure but i am getting an
error.
create PROCEDURE prdUpdate_Year
@year varchar(40)
As
@year = Mid(Newfiels,1,4)
UPDATE AddressBook SET AddressBook.Year = @year;
GO
Thanks
View 2 Replies
View Related
Jun 5, 2000
Hi,
I am trying to break up a column "name" into 2 columns "first name" and "last name". The name colum is currently "lastname, firstname". Is there an easy way to do this in SQL 6.5?
I successfully extracted the first name using:
firstname = rtrim(substring(name, (charindex(',', name)), 25))
But I am having trouble doing the lastname. Please help.
Thanks so much!
Laura
View 3 Replies
View Related
Dec 6, 2000
Hi,
I want to write a query which selects ind and
clcode where
ind(individual) has taken all 3 classes(clcode) 15, 16 and 17.
for example: it should only return data for ind 1 from the following data as only ind 1 has taken all three classes.
How can I write it?
table: ind_history
ind clcode
----------- -----------
1 16
1 17
2 17
1 15
2 16
3 11
4 15
View 1 Replies
View Related
Aug 4, 2004
I need help with a query that I want to incorporate into a scheduled DTS within SQL Server 2000. I have a process that brings in records from an Excel file, compares that day's records with any related information already stored in the database, then saves a table of joined records. This leaves me with any matches to the data. I need to filter out all but the most current record, which would be identified by a column named [DATE]. Ex:
Table tblMatchedRecords
M BLah Blah2 [DATE]
1 this that 20040101
2 this them 20040102
3 this that 20040630
In this example, I would like to have the record with [DATE] = 20040630 kept, and the others deleted. All columns do not always have to match exactly. I want to be able to specify which fields that need to match and pull only the latest date.
Make sense? Can anyone offer any suggestions?
View 4 Replies
View Related
May 9, 2007
I have a few variables declared
@amount=100000 (any big int)
@pamount=100000
@a1,@a2 - thorugh @25 -- each a bigint
@p1,@p2,@p3
@id - int
if @id is an odd number I need to randomly change @amount-@a1 (randomly to @a1 - @a25 so it ends up being any of 25 values)
and then @pamount randomly= to either @p1,@p2 or @p3
Can someone help me do the sql for this?
it will be within my stored procedure
View 5 Replies
View Related
Nov 30, 2007
Hi
Is there any sp or command to deactivate and activate all constraints in a database...
Thanks in Advance
RKNAIR
View 6 Replies
View Related
Mar 4, 2008
I have 2 sql server that are registered and linked.
If I have a table in server 1 that I want to make a backup of to server 2, how would I do that in t-sqlv(if the table did not already exisit on the second server)
Thanks
"Impossible is Nothing"
View 4 Replies
View Related
Aug 22, 2005
A stored procedure was running slowly so I took the code, removed thesubselect and included a join, then took the max and included as partof a correlated subquery.The result is below, however, this is no improvement over the original.An advice would be greatly appreciated.SELECT FSALT.FUNDING_LINE_TYPE_ID,A.PAYMENT_PERIOD_ID,A.CASH AS CASH,A.VOLUME AS VOLUMEFROM ACTUALS AINNER JOIN (SELECT MAX(COLLECTION_PAYMENT_PERIOD_*ID) AS CPP FROMACTUALS ACT WHERE COLLECTION_PAYMENT_PERIOD_ID<=*456) AS O ON O.CPP =A.COLLECTION_PAYMENT_PERIOD_IDINNER JOIN FS_ACTUAL_LINE_TYPES FSALT ON FSALT.FS_ACTUAL_LINE_TYPE_ID =A.FS_ACTUAL_LINE_TYPE_IDINNER JOIN PAYMENT_PERIODS PP ON PP.PAYMENT_PERIOD_ID =A.PAYMENT_PERIOD_IDWHEREA.ORG_ID=24771AND A.LSC_ORG_ID=5816AND PP.FUNDING_STREAM_ID=5AND PP.FUNDING_PERIOD_ID=6GROUP BYFSALT.FUNDING_LINE_TYPE_ID,A.PAYMENT_PERIOD_ID, A.CASH, A.VOLUME
View 2 Replies
View Related
Feb 22, 2008
I have a table that has a datetime field that needs a calculated time difference created when querying the table. I'm new to TSQL and I've been banging my head on this one. There is a time window that must be dealt with as well, so that any time that falls outside if the time window gets assigned a zero value (not calculated). The last record inside the window and the first record inside the window get calculated based on a given start and end time. The time outside the window is 7PM to 7AM. Here's an example:
in/outside window Time Value Calculation Time Diff (in minutes)
inside window time1 = '13:15:00' null the first record is always null
inside window time2 = '14:15:00' time2-time1 60
inside window time3 = '18:50:00' time3-time2 275
outside window time4 = '19:10:00' 18:59:59 - time3 10
outside window time5 = '21:00:00' 0 0
outside window time6 = '06:30:00' 0 0
outsidw window time7 = '06:45:00' 0 0
inside window time8 = '07:45:00' time8 - 07:00:00 15
How can this be done using TSQL? Let me know if more info is needed. Thanks!
View 8 Replies
View Related
Dec 25, 2007
Hi guys,
The query below is running ok.
Code Block
USE test2006mdt
if object_id('AuxTable20071224132300') is not null exec('DROP TABLE AuxTable20071224132300')
SELECT DISTINCT
Stock.ACCOUNTKEY AS 'Stock.ACCOUNTKEY',
Stock.DOCNUMBER AS 'Stock.DOCNUMBER',
Stock.DOCUMENTID AS 'Stock.DOCUMENTID',
CASE WHEN Cast(Stock.DOCUMENTID as int) In ('1','35') THEN 'IN# ' + Cast(Stock.DOCNUMBER as varchar) WHEN Cast(Stock.DOCUMENTID as int) In ('3','120') THEN 'CM# ' + Cast(Stock.DOCNUMBER as varchar) ELSE '' END AS 'Invoice #',
Stock.VALUEDATE AS 'Stock.VALUEDATE',
Stock.TFTAL AS 'Stock.TFTAL',
Stock.CURRENCY AS 'Stock.CURRENCY',
CASE WHEN ReceiptJurnalMatch.SUF Is NULL THEN '0' ELSE -1 * ReceiptJurnalMatch.SUF END AS 'ReceiptJurnalMatch.SUF',
Stock.ID AS 'Stock.ID',
CASE WHEN ReceiptJurnalMatch.FULLMATCH Is NULL THEN '0' ELSE ReceiptJurnalMatch.FULLMATCH END AS 'ReceiptJurnalMatch.FULLMATCH'
INTO AuxTable20071224132300
FROM
RECEIPTJURNALMATCH
RIGHT OUTER JOIN JURNALTRANSMOVES ON RECEIPTJURNALMATCH.JURNALTRANSID = JURNALTRANSMOVES.ID
RIGHT OUTER JOIN STOCK
INNER JOIN ACCOUNTS ON STOCK.ACCOUNTKEY = ACCOUNTS.ACCOUNTKEY
INNER JOIN JURNALTRANS ON STOCK.ID = JURNALTRANS.STOCKID ON JURNALTRANSMOVES.TRANSID = JURNALTRANS.TRANSID
LEFT OUTER JOIN STOCKMOVES ON STOCK.ID = STOCKMOVES.STOCKID
WHERE
Stock.ACCOUNTKEY Between 'Account01' AND 'Account01'
AND Stock.Status Not In ('0','2')
AND Stock.DOCUMENTID In ('1','35','3','120')
ORDER BY Stock.ACCOUNTKEY
SELECT DISTINCT
[Stock.ACCOUNTKEY] AS 'Stock.ACCOUNTKEY',
[Stock.DOCNUMBER] AS 'Stock.DOCNUMBER',
[Stock.DOCUMENTID] AS 'Stock.DOCUMENTID',
[Invoice #] AS 'Invoice #',
[Stock.VALUEDATE] AS 'Stock.VALUEDATE',
[Stock.TFTAL] AS 'Stock.TFTAL',
[Stock.CURRENCY] AS 'Stock.CURRENCY',
Sum([ReceiptJurnalMatch.SUF]) AS 'Sum([ReceiptJurnalMatch.SUF])',
CASE WHEN CAST(DATEDIFF(dd,[Stock.VALUEDATE],GETDATE()) AS int) <= 30 THEN [Stock.TFTAL] - Sum([ReceiptJurnalMatch.SUF]) ELSE '' END AS '1-30',
CASE WHEN CAST(DATEDIFF(dd,[Stock.VALUEDATE],GETDATE()) AS int) BETWEEN 31 AND 60 THEN [Stock.TFTAL] - Sum([ReceiptJurnalMatch.SUF]) ELSE '' END AS '31-60',
CASE WHEN CAST(DATEDIFF(dd,[Stock.VALUEDATE],GETDATE()) AS int) BETWEEN 61 AND 90 THEN [Stock.TFTAL] - Sum([ReceiptJurnalMatch.SUF]) ELSE '' END AS '61-90',
CASE WHEN CAST(DATEDIFF(dd,[Stock.VALUEDATE],GETDATE()) AS int) > 90 THEN [Stock.TFTAL] - Sum([ReceiptJurnalMatch.SUF]) ELSE '' END AS '>> 90',
[Stock.TFTAL] - Sum([ReceiptJurnalMatch.SUF]) AS 'Balance'
FROM AuxTable20071224132300
WHERE Balance <> 0 ==> Getting ERROR!!!
GROUP BY [Stock.ACCOUNTKEY], [Stock.DOCNUMBER], [Stock.DOCUMENTID], [Invoice #], [Stock.VALUEDATE], [Stock.CURRENCY], [Stock.TFTAL]
The results are:
ACCOUNTKEY DOCNUMBER DOCUMENTID Invoice # VALUEDATE TFTAL CURRENCY SUF 1-30 31-60 61-90 >> 90 Balance
Account01 16917 35 IN# 16917 2007-12-25 00:00:00.000 15000 Euro 15000 0 0 0 0 0
Account01 16918 35 IN# 16918 2007-12-25 00:00:00.000 300 Euro 300 0 0 0 0 0
Account01 16919 35 IN# 16919 2007-12-25 00:00:00.000 110 Euro 110 0 0 0 0 0
Account01 16920 35 IN# 16920 2007-11-10 00:00:00.000 5 Euro 5 0 0 0 0 0
I inted to add a WHERE clause in order to Show Only Invoices with Balance <> 0, but getting Error.
Thanks in advance for any help.
Note: I am working under SQL SERVER 2000
Aldo.
View 8 Replies
View Related