Making A Stored Procedure In MS-SQL 2000
Jul 23, 2005
Hi,
Sorry, this is a very easy question. I have to create a stored
procedure in a SQL SERVER Database.
I have read lots on MSDN about the syntax of this stored procedure :
ie.
CREATE PROCEDURE spGetContctDetails
AS
-- get everything out of contact table
SELECT * FROM tblContact
but I cannot find anywhere how to actually add this procedure, so that
it is accessable in my VB.NET program.
What I am asking is : what screen do I type this into? Is it Query
Analyzer, if so where?
Its got me oh so confused. When I've got time i'll read all about SQL
Server, but for this morning I need to know how to simply add that
Stored Procedure to my database.
Thanks LOADS for any help.
View 1 Replies
ADVERTISEMENT
Jun 13, 2007
Hi. I have a stored procedure that I'm interacting with through vb.net... the stored procedure logic, by itself, runs in query analyzer, but when I run it from the code side using the stored procedure, it dies. Now, that said, I'm not a pro at writing a stored procedure, so you might look at this and gasp in horror.
I'm executing a three-staged query, all of which are using temp tables, the final of which is what I'm using for my datagrid import. The temp table name I'm using doesn't work... it's not accepted in the SP and stops the execution of the query stating "invalid table name."
Not being a guru at this, I dont know why it runs in Query Analyzer but not w/i the SP. Can someone look at this and help?
(If its grossly written and there's a better way, I wouldn't be offended to be told that either. I"m looking for ways to write cleaner, faster code)
Here is the SP, any suggestions are very very appreciated.
Thanks so much!
CREATE PROCEDURE sp_PCPPanel_Summary
(@strWHEREMale as varchar(500), @strWHEREFemale as varchar(500))
AS
EXEC('
SELECT
Gender, RealAge, WeightedAge, FWeight, Mweight, AccountNum, PatLastName, PatFirstName, PatAddress, Patcity, PatState , PatZip, Tertiary, PatientStatusKey, InsClass, InsClassDesc, PCPDr, PCPClass, InsurancePlan, CarrierKey, CarrierName, PlanName, Age
INTO #tblTempPCP
FROM(
SELECT tblPCP.AccountNum, tblPCP.PatLastName, tblPCP.PatFirstName, tblPCP.PatAddress, tblPCP.PatCity, tblPCP.PatState, tblPCP.PatZip, tblPCP.PatPhone, tblPCP.DOB, tblPCP.Age, tblPCP.Gender, tblPCP.InsurancePlan, tblPCP.PCPClass, tblPCP.CarrierName, tblPCP.CarrierKey, tblPCP.PCPDr, tblPCP.PlanName, tblPCP.InsAddress, tblPCP.InsCity, tblPCP.InsState, tblPCP.InsZip, tblPCP.Tertiary, tblPCP.PatientStatusKey, dbo.tblPanelWeights.WeightedAge, dbo.tblPanelWeights.Category, 0 as MWeight, dbo.tblPanelWeights.Female as FWeight, dbo.tblPanelWeights.RealAge, tblPCP.InsClass, tblPCP.InsClassDesc, tblPCP.ApptDate FROM dbo.tblPanelWeights RIGHT OUTER JOIN dbo.[vwPCP+Continuity] tblPCP ON dbo.tblPanelWeights.RealAge = tblPCP.Age ' + @strWHEREFEMALE + '
UNION SELECT tblPCP.AccountNum, tblPCP.PatLastName, tblPCP.PatFirstName, tblPCP.PatAddress, tblPCP.PatCity, tblPCP.PatState, tblPCP.PatZip, tblPCP.PatPhone, tblPCP.DOB, tblPCP.Age, tblPCP.Gender, tblPCP.InsurancePlan, tblPCP.PCPClass, tblPCP.CarrierName, tblPCP.CarrierKey, tblPCP.PCPDr, tblPCP.PlanName, tblPCP.InsAddress, tblPCP.InsCity, tblPCP.InsState, tblPCP.InsZip, tblPCP.Tertiary, tblPCP.PatientStatusKey, dbo.tblPanelWeights.WeightedAge, dbo.tblPanelWeights.Category, dbo.tblPanelWeights.Male as MWeight, 0 as FWeight, dbo.tblPanelWeights.RealAge, tblPCP.InsClass, tblPCP.InsClassDesc, tblPCP.ApptDate FROM dbo.tblPanelWeights RIGHT OUTER JOIN dbo.[vwPCP+Continuity] tblPCP ON dbo.tblPanelWeights.RealAge = tblPCP.Age ' + @strWHEREMALE + '
) unionWEIGHTS
GROUP BY Gender, RealAge, WeightedAge, FWeight, Mweight, AccountNum, PatLastName, PatFirstName, PatAddress, patcity, patState , patZip, Tertiary, PatientStatusKey, InsClass, InsClassDesc, PCPDr, PCPClass, InsurancePlan, CarrierKey, CarrierName, PlanName, Age
ORDER BY realage
')
SELECT isnull(cast(RealAge as varchar), 'Unknown') as AgeRange, RealAge as AgeSort, gender, mweight, fweight, [Male] = sum(case when gender = 'M' then 1 else 0 end), [Female] = sum(case when gender = 'F' then 1 else 0 end), count(*) as Totalinto #tblTempPCP2
FROM #tblTempPCPgroup by realage, gender, mweight, fweight
Select AgeRange, AgeSort, [MALE], [FEMALE], [Male Weighted] = case when gender = 'M' then Sum(MWeight * [MALE]) end, [Female Weighted] = case when gender = 'F' then Sum(FWeight * [FEMALE]) endfrom #tblTempPCP2group by AgeRange, AgeSort, [MALE], [FEMALE], gender, totalorder by AgeSortGO
View 3 Replies
View Related
Jul 20, 2005
Hi,I have a requirement to update a table in SQL Server through a storedprocedure,the stored procedure should run periodically, say once in a month, andupdate the table.I should not use any external programs to call thestored procedure, is there any other way to do it without using anexternal programs.Thanks in advance,Rajan
View 2 Replies
View Related
May 29, 2008
I am not sure if this is a correct place to post this question. i am making a simple pay bill system, require people set a schedule that pays bill, then save it into database, when the time come, it auto transfers the money, i am thinking if i can do this in a store procedure. here is the interface:From Account:To Payee:Amount:ScheduleDate: Save the schedule task View scheduled task
View 5 Replies
View Related
Oct 14, 2007
I am calling a stored procedure (say X) and from that stored procedure (i mean X) i want to call another stored procedure (say Y)asynchoronoulsy. Once stored procedure X is completed then i want to return execution to main program. In background, Stored procedure Y will contiue his work. Please let me know how to do that using SQL Server 2000 and ASP.NET 2.
View 3 Replies
View Related
Jul 20, 2005
I have a 6.5 db that I want to create a copy of, I can move it to eithera machine running 7 or 2000. I am more used to doing this in Oracle sopls bear with me...I don't want to have any downtime on the 6.5 db, so I'm thinking perhapsimport is the best way to go? I am assuming that 6.5 backups are notcomaptible with either 7 or 2000 restore, or I'd go that route.The database in question is fairly simple, pretty well just tables fullof data, no stored procs...suggestions?TIA
View 4 Replies
View Related
Jan 18, 2007
I need to automate the following function. I know I can do this in .NET but I need to have a DTS package setup so it executes every evening.
I have a view that produces a list of sales errors. I want to grab the SaleID from each record and insert a record into a "Current Queue" table.
Here is another example of what I'm trying to do...
SELECT SaleID FROM vw_SalesErrors
- with the results of the SQL statement above
INSERT INTO tbl_QueueRecords
(SaleID, QueueID)
VALUES
(@SaleID, 14)
I'm assuming there is a way to automate this into a single stored procedure or at least a DTS pacakge.
Thanks for all of your help.
View 2 Replies
View Related
Dec 18, 2006
I have a MSSQL2000 box with a large database containing circa 150 SP's.I want to move the DB to another SQL machine, but many of the SP's havereferences to the name of the current machine. Is there any way tobatch edit the procedures to refer to the new server, disassociatingthe old machine completely?Tia,Graham
View 1 Replies
View Related
Jul 20, 2005
I am trying to get the DTS Execute SQL task to run a simple sql server 2000no-parameter stored procedure.The procedure runs without error when using SQL Analyzer but DTS Execute SQLreports "could not find stored procedure "[dbo].[test]"The stored procedure is as follows:create procedure test asdeclare tnames_cursor CURSORforselect database_name, tmp_table_name from[DW_Dimensions].[dbo].[vw_dimension_temporary_tables_active]open tnames_cursordeclare @tablename sysnamedeclare @databasename sysnamewhile (@@FETCH_STATUS <> -1)beginselect @databasename = rtrim(@databasename)select @tablename = rtrim(@tablename)exec ("delete from " + @databasename + ".dbo." + @tablename)fetch next from tnames_cursor into @databasename, @tablenameendclose tnames_cursordeallocate tnames_cursorGOAny ideas?
View 1 Replies
View Related
Feb 1, 2008
I have a stored procedure that builds a sql statement and executes it. When run in Query Analyzer it runs successfully and displays records as it should. When I open a recordset with the stored procedure from VBA it executes the codes but doesn't open the recordset.
The store procedure is:
ALTER PROCEDURE dbo.spTest
AS
DECLARE @sColumns varchar(2000)
DECLARE @sFrom varchar(2000)
DECLARE @sWhere varchar(2000)
DECLARE @sSqlString AS nvarchar(2000)
SET @sColumns = 'dbo.tblDoctor.lastname '
SET @sFrom = 'FROM dbo.tbldoctor '
SET @sWhere = 'WHERE dbo.tbldoctor.doctorcode is not null '
SET @sSqlString = 'SELECT ' + @scolumns + ' ' + @sFrom + ' ' + @swhere PRINT '@scolumns ' + @scolumns
PRINT '@sfrom ' + @sfrom PRINT '@swhere ' + @swhere PRINT 'sqlstring ' + @sSqlstring
EXEC Sp_executesql @sSqlString
The VBA code is:
Private Sub Command0_Click()
Dim cn As Connection
Dim rs As New ADODB.Recordset
Dim strsql As String
Set cn = CurrentProject.Connection
strsql = "exec spTest"
With rs
.Source = strsql
.ActiveConnection = cn
.CursorType = adOpenKeyset
.LockType = adLockReadOnly
.Open
End With
Debug.Print rs.RecordCount & " records found"
End Sub
When it hits the line with rs.recordcount it displays the following error: "Operation is not allowed when object is closed" referring to the rs recordset never being opened.
Any suggestions?
View 4 Replies
View Related
May 18, 2008
Hi sir ,
That is my Stored pro. which search in Sales table .
- I do NOT know which parameters will be sent and which will be null.
- I write sqlString which dynamically changed based on which parameters sent.
Here is my code:
Code Snippet
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Alter PROCEDURE SearchInSales
@ID bigint,
@AmmountPaid bigint,
@AmmountDelayed bigint,
@Quantity bigint
AS
BEGIN
SET NOCOUNT ON;
Declare @sqlStr nvarchar(200)
set @sqlStr='SELECT * FROM Sales WHERE '
if @ID is not null
set @sqlStr = @sqlStr + 'ID = ' + cast(@ID as nvarchar(50))
else
BEGIN
if @AmmountPaid is not null
set @sqlStr = @sqlStr + 'AmmountPaid = ' + cast(@AmmountPaid as nvarchar(50))
if @AmmountDelayed is not null
BEGIN
if len(@sqlStr)>25 -- check if @sqlStr has any of pre. conditions
set @sqlStr = @sqlStr + ' AND '
set @sqlStr = @sqlStr + 'AmmountDelayed = ' + cast(@AmmountDelayed as nvarchar(50))
END
if @Quantity is not null
BEGIN
if len(@sqlStr)>25 -- check if @sqlStr has any of pre. conditions
set @sqlStr = @sqlStr + ' AND '
set @sqlStr = @sqlStr + 'Quantity = ' + cast(@Quantity as nvarchar(50))
END
END
EXEC(@sqlStr)
END
GO
Is there way better than I did?
View 7 Replies
View Related
Jul 30, 2007
Hi
This is seshu.
Is there any way to find out the last used stored procedure.
Let me know about this one.
View 1 Replies
View Related
Apr 1, 2005
I'm using Java to connect to a SQL Server 2000 database. I connect using the Driver Manager with Sun's odbc driver ( sun.jdbc.odbc.JdbcOdbcDriver ) or I can use the jdbc driver provided by Microsoft (com.microsoft.jdbc.sqlserver.SQLServerDriver)
The Java application makes 1 Connection.
Within the database there exists a stored procedure that updates 2 Tables. The tables have a fixed number of rows that get updated continuously by calls to this stored procedure.
The Java application has a thread pool of 15 threads that create 15 CallableStatements (1 per thread) using the same instance of the Connection object.
According the the Microsoft JDBC driver docs, 1 Connection with multiple calls to the Callable statements is how it's supposed to be done. The following is an excerpt from Microsoft's "SQL Server 2000 Driver for JDBC User’s Guide and Reference" (page 86) regarding Connection Managment:
Managing Connections
Connection management is important to application performance. Optimize your application by connecting once and using multiple statement objects, instead of performing multiple connections. Avoid connecting to a data source after establishing an initial connection.
This is precisely what I'm doing, but I do not know if the the stored procedures are being run concurrently, the documentation does not tell me.
So my question: What is happening inside SQL Server 2000?
View 2 Replies
View Related
May 19, 2004
Hi everyone,
I am new to the forum and I have a problem with a stored procedure in SQL Server 2000. I use a stored procedure that returns a string but the problem is that my variable is empty at least I think it's empty.
With the code below the variable is not empty:
set @Ssql = 'select Cust_Company_id, fix_price from GEC_FixPrice where priority > 0 and cust_company_id like ' + char(39) + @InvoiceLine_CustCompanyid + char(39) + ''
But when I use the code below it's empty
- set @sSql = 'select Cust_Company_id, fix_price from GEC_FixPrice where priority > 0 '
- set @sSql = @sSql + ' and cust_company_id like ' + char(39) + @InvoiceLine_CustCompanyid + char(39) + ''
I also tried this :
- set @Start = 'select Cust_Company_id, fix_price from GEC_FixPrice where priority > 0 '
- set @End = ' and cust_company_id like ' + char(39) + @InvoiceLine_CustCompanyid + char(39) + ''
- set @sSql = @Start + @End
This works also, so I don't get why the second example won't work and the second example is the one I want to use.
So does anyone has a clue :confused:
thx in advance,
grtz
Loki2600
View 2 Replies
View Related
Jul 20, 2005
Hi All,I have a table that holds pregenerated member IDs.This table is used to assign an available member id to web sitevisitors who choose to register with the siteSo, conceptually the process has been, from the site (in ASP), to:- select the top record from the members table where the assigned flag= 0- update the row with details about the new member and change theassigned flag to 1- return the selected member id to the web pageNow I'm dealing with the idea that there may be brief, high trafficperiods of registration, so I'm trying to build a method (storedprocedure?) that will ensure the same member id isn't returned by theselect statement if more than 1 request to register happens at thesame instant.So, my question is, is there a way, once a record has been selected,to exclude that record from other select requests, within the boundsof a stored procedure?ie:- select statement is executed and row is instantly locked; any otherselect statement running at that exact moment will receive a differentrow returned and sill similarly lock it, ad nauseum for as manysimultaneous select statements as take place- row is updated with details and flag is updated to indicate themember id is no longer unassigned- row is released for general purposes etcIf what I'm suggesting above isn't practical, can anyone help meidentify a different way of achieving the same result?Any help immensely, immensely appreciated!Much warmth,Murray
View 12 Replies
View Related
Aug 15, 2007
I have no idea about how can I use xp_sendmail
when I try to use it this error displayed on the screen.
There is no default mail client or the current mail client cannot fulfill the messaging request. Please run Microsoft Outlook and set it as the default mail ...
View 3 Replies
View Related
Mar 12, 2007
Can anyone of you help me in finding online - resources to write extended stored procedure for Sql Server 2000 using C#.
Thank you,
Andy Rogers
View 1 Replies
View Related
Jul 23, 2007
Hi,
I m wanting a stored procedure to pass an XML string from a stored procedure to my application. Whats the best way to achieve this?
Hope you can help
Thanks
Paul
View 10 Replies
View Related
May 19, 2007
I am developing a windows application in VB.Net 2005 and Database is SQl Server 2000.I want to insert, update and delete records from a master table which has 8 columns.So should I write a stored procedure for this or write three queries and execute them in code.I haven't used stored procedure before. What will be advantages of using stored procedures?And tell me how to write stored procedure to insert,update and delete. Then how to call it in VB.Net code.
View 7 Replies
View Related
Mar 29, 2007
Hi Everybody,
I am trying to update a column Percentage in a table named Critical Doctors with a column named
PercentTime from tblPercent table, Where the column Doctor matches with any DoctorId from
tblPercent.
I am getting an error message for the following query.
Have Two tables
1.CriticalDoctors
2.tblPercent
update CriticalDoctors set Percentage =
(select PercentTime from tblPercent)
where CriticalDoctors.Doctor = (select DoctorId from tblPercent)
Server: Msg 512, Level 16, State 1, Line 1
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.
Pls give me reply on how to write a stored procedure so that I can equate the percentage column
with one value and also check the condition with one value.
Thanking you guys in advance.
madhav
View 4 Replies
View Related
Apr 19, 2007
Hi there everybody,
I am writing a sales managing software using C# in .NET 2005.
The program was used to work properly with sql server 2000.
I decided to write a "FILE Version" of sofware using sql server express 2005 , and detached db from 2000 , attaching it to 2005 using AttachDBFileName clause in connection string.
But the problem is when program executes something like this:
EXEC [AddOrder] ...
two rows inserted instead of one.and when I use server explorer of VS2005 to launch SP, it works fine.
I should mention again that same code works correctly when I change connection string and force it to use sqlserver 2000.
Any ideas?
Kind Regards: Ali
View 6 Replies
View Related
Jul 20, 2005
I was using the SQL 2000 stored procedure wizard to create storedprocedures. I can create insert, delete and update SPs however I amnot able to create the select SP. The wizard does not offer the optionof selecting "select" type SP. thank you for your replyscompraj
View 1 Replies
View Related
Jul 20, 2005
I have this stored procedure that takes a few parameters like date andmerchant ID, and basically goes through a set of if-then statements to builda SQL SELECT string.When we upgraded from SQL Server 7.0 to 2000, the stored procedure stillworked from Query Analyzer, but not in BCP. It used to work in BCP justfine with 7.0. The error I get now is:SQLState = S1000, NativeError = 0Error = [Microsoft][ODBC SQL Server Driver]BCP host-files must containat least one columnWhat's really strange is, if I instruct the stored procedure to simply printthe SELECT string, then cut-and-paste it into the end of stored procedurecode (assigning it to the variable that already contains the SELECT string),then it works from BCP.Any help would be greatly appreciated.Aston
View 1 Replies
View Related
Mar 13, 2007
Hi,
I am not understanding this part of the problem. I am currently reusing a stored procedure that has a ".." as part of the select statement.
I can't put the select statement up here due to privacy but I have found the error where the error states the following:-
Invalid Column Prefix: AM, invalid table name.
I noticed that part of the select statement was the following:-
AM..Field1
I tried executing this stored procedure in the query analyzer and it works fine, but when I tried executing it in SSRS, it gives me the error. After searching through the internet for possible causes, I found out that it was the ".." was giving the error. Anyone knows why ? I found out that it was supposed to bypass any users and permissions to the table.
Thakns !
Bernard
View 1 Replies
View Related
Nov 8, 2006
I have a rather complex sp that runs for 4 minutes in SQL2000. It computes some messy oil and gas revenue/cost transactions. It involves lots of calls to functions that return single values of all types and also returns recordsets. There are all kinds of joins with temp and memory tables, etc. Just a mess, but it works. However, in SQL2005, it runs and apparently hangs, as it never ends.
I have run the Upgrade Advisor and otherwise, have not found any information that tells me that there are issues with functions or SQL-specific functions, tables, etc. that might cause this. Does anyone on this forum have some pointers on where I might look for assistance on this matter? Surely someone knows something about things working differently in 2005.
Thanks,
Jim
View 4 Replies
View Related
Mar 3, 2008
can I send a mail by stored procedure?
View 5 Replies
View Related
May 16, 2006
Hi ,
I have around 5 databases with same structure used to store data for different locations and services.
I have created an intermediate database which will have all the stored procedures to access data from above 5 databases.
My queries are common to all the databases. so,I would like to pass database name as an argument to my stored proc and execure query on specified database.
I tried this doing using "USE Databasename " Command. but it says ...We can not use "USE command " in stored proc or triggers. so ..what i did is ..
--------------------------------------------------------------------------------------------------------------
CREATE PROCEDURE TestDB_access(@dbname varchar(100))
AS
BEGIN
DECLARE @localDB varchar(100)
Set @LocalDB=@dbname
if @LocalDB='XYZ'
EXEC ('USE XYZ ')
elseif @LocalDB='ABC'
EXEC ('USE ABC')
Select * from Mytable
END
---------------------------------------------------------------------------------------------------------------
When I run this from my database , it gives me an error "unable to find table "mytable".
What is the best way to make my queries work with all the databases.
Thanks in advance
Venu Yankarla
View 4 Replies
View Related
Oct 27, 2006
Hi, I have a problem with "database output" window in executing a select-sp in vs 2005 standard. The db is a sql server 2000 one.When I execute the sp within VS, the database output correctly displays the execution information:No rows affected.(1 row(s) returned)@RETURN_VALUE = 3 but I can't see the returned rows (3 rows are returned); I only see the column names and no data.Running [dbo].[spBkm_GetList] ( @IDUser = <DEFAULT>, [.........]).IDBkm UIBkm IDUser --------------------- -------------------------------------- ---------
No rows affected. If I run the same sp in Sql Server Manager Studio Express it correctly shows the data of the 3 rows returned. The sp uses EXEC sp_executesql @Sql, @ParamList, ...... for executing the sql statement and the last line of sp is RETURN @@ROWCOUNTI've tried removing the "RETURN @@ROWCOUNT" with no success. The problem affects only one sp, the others, which are absolutely similar, work properly . I don't know what is the problem...Any idea?Thanks in advance
View 1 Replies
View Related
Mar 4, 2004
Hy all.
My main goal would be to create some kind of map of the database, wich contains information of all connecting fields, including wich fields has key references to the other one and wich table. I'd like to have a table wich shows all the database connections tablename, field, field/table_key (from or to the key points), field_key_type (prymary or foreign)
So I thaugh to get sp_fkeys and sp_pkeys from master table and inner joining their results, but I simplay cannot "catch" their result sets. The script must have been written in SQL.
Obviously I'd like to do this:
SELECT * FROM EXEC sp_fkeys @table_name = 'xy'
of course it is not working this way, but I'd like something like this.
Please help! Thanx!
View 3 Replies
View Related
Jul 20, 2005
I am trying to run xp_cmdshell from the Query Analyzer using SQLServer 2000 running on Windows 98.It seems like it should be simple - I'm typingxp_cmdshell 'dir *.exe'in the Query Analyzer in the Master db. I'm logged in as sa.The timer starts running and never stops. No error message.Can anyone PLEASE help me with this? Any suggestions would beappreciated. Are SQL Server 2000 extended stored procedures notsupported in Windows 98? I've tried searching the Knowledge Base butcan't find anything.Thanks!
View 1 Replies
View Related
Mar 3, 2008
Can I create an excel file by stored procedure?
View 2 Replies
View Related
Nov 18, 2005
I'm trying to set up Service Broker Services on SQL 2005 x86. I've got two services set up, and a stored procedure associated with one of them.
View 5 Replies
View Related
Nov 30, 2007
I hav the following problem. I have written an stored procedure in sql server 2000 as the following
CREATE PROCEDURE dbo.pa_rellena
@pFechaInicio datetime
AS
declare @pFechaFin datetime
declare @auxcod_cen char(10)
declare @importeEfectivo decimal(17,2)
declare @importeTarjetas1 decimal(17,2)
declare @importeTarjetas2 decimal(17,2)
declare @importeVales decimal(17,2)
declare @importeTalones decimal(17,2)
declare @importeGastos decimal(17,2)
select @pFechaFin=@pFechaInicio+1
--Borramos las tablas temporales si las hemos creado con anterioridad y no se han borrado
if object_id('tmpCentros') is not null
drop table tmpCentros
if object_id('tmpCentros2') is not null
drop table tmpCentros2
if object_id('tmpMaxCajas') is not null
drop table tmpMaxCajas
if object_id('tmpCajasCentro') is not null
drop table tmpCajasCentro
if object_id('tmpVales') is not null
drop table tmpVales
if object_id('tmpDiarioEfectivo') is not null
drop table tmpDiarioEfectivo
if object_id('tmpDiarioTalones') is not null
drop table tmpDiarioTalones
if object_id('tmpDiarioTarjetas') is not null
drop table tmpDiarioTarjetas
if object_id('tmpDiarioSegundaForma') is not null
drop table tmpDiarioSegundaForma
if object_id('tmpDiarioGastosTarjetas') is not null
drop table tmpDiarioGastosTarjetas
if object_id('temp1') is not null
drop table temp1
--Seleccionamos todos los centros de Salvador Bachiller
select * into tmpCentros2
from centros
where centros.tienda=1
order by cod_cen
--Seleccionamos el maximo de cajas por cada centro
select cod_cen, max(cod_caja) as cajas into tmpMaxCajas
from cierrecaja
where fecha>=@pFechaInicio and fecha<@pFechaFin
group by cod_cen
order by cod_cen
--Mezclamos los centros con el maximo de cajas
select c.cod_cen, c.Centro, c.Direccion, c.localidad, c.provincia, c.cpostal, c.telefono, m.cajas, operaciones, cajas_tot, tienda, franquicia into tmpCentros
from tmpCentros2 as c left outer join tmpMaxCajas as m on c.cod_cen=m.cod_cen
--Cajas por centro
select distinct cod_cen as cod_cen, cod_caja as cod_caja into tmpCajasCentro
from cierrecaja
where fecha>=@pFechaInicio and fecha<@pFechaFin
--Los vales de cada centro
select cod_cen,sum(importe) as imp1 into tmpVales
from vales where
fecha>=@pFechaInicio and fecha<@pFechaFin
group by cod_cen
--Efectivo de cada centro
select cod_cen,'01' as vendedor,'EFECTIVO' as descripcion, (sum(diario.TotEuro)-Sum(Diario.Imppa2)) as importe1,0 as exp1, (sum(Diario.TotEuro)-sum(Diario.imppa2)) as importe2 into tmpDiarioEfectivo
from diario
where fecha>=@pFechaInicio and fecha<@pFechaFin and cod_cen in (select cod_cen from tmpCentros) and cod_caja in (select cod_caja from tmpCajasCentro) and diario.cod_pago='01'
group by cod_cen
--Talones por centro
select centros.cod_cen,'02' as vendedor,'TALONES' as descripcion, sum(diario.TotEuro) as importe1,0 as exp1, sum(Diario.TotEuro) as importe2 into tmpDiarioTalones
from centros inner join diario on centros.cod_cen=diario.cod_cen
where fecha>=@pFechaInicio and fecha<@pFechaFin and diario.cod_cen in (select cod_cen from tmpCentros) and cod_caja in (select cod_caja from tmpCajasCentro) and diario.cod_pago='02'
group by centros.cod_cen
--Tarjetas por centro
select cod_cen,'03' as vendedor,'TARJETAS' as descripcion, sum(diario.TotEuro) as importe1,0 as exp1, sum(Diario.TotEuro*(FPago.Descuento/100)) as importe2, sum(Diario.TotEuro) - sum(Diario.TotEuro*(FPago.Descuento/100)) as importe3 into tmpDiarioTarjetas
from FPago left join Diario on fpago.Cod_pago=Diario.cod_pago
where fecha>=@pFechaInicio and fecha<@pFechaFin and cod_cen in (select cod_cen from tmpCentros) and cod_caja in (select cod_caja from tmpCajasCentro) and Fpago.Descuento<>0
group by cod_cen
--Segunda Froma de Pago
select cod_cen,'03' as vendedor,'TARJETAS' as descripcion,sum(diario.imppa2) as importe1 into tmpDiarioSegundaForma
from fpago left join Diario on Fpago.cod_pago=diario.cod_pa1
where fPago.cod_pago<>'99' and fecha>=@pfechaInicio and fecha<@pFechaFin and cod_cen in (select cod_cen from tmpCentros) and cod_caja in (select cod_caja from tmpCajasCentro) and Fpago.Descuento<>0
group by cod_cen
--Comisiones tarjetas de pago
select cod_cen,'10' as vendedor, 'GASTOS (-)' as descripcion, sum(Diario.imppa2*(fPago.Descuento/100)) as importe2 into tmpDiarioGastosTarjetas
from Fpago left join Diario on FPago.cod_pago= Diario.cod_pa1
where fPago.cod_pago<>'99' and fecha>=@pFechaInicio and fecha<@pFechaFin and cod_cen in (select cod_cen from tmpCentros) and cod_caja in (select cod_caja from tmpCajasCentro) and Fpago.Descuento<>0
group by cod_cen
/*
--Venta neta por centro
declare cursortemporal cursor for select cod_cen from TmpCentros2
open cursortemporal
delete detallecaja_aux
fetch next from cursortemporal into @auxcod_cen
while @@fetch_status=0
Begin
select @importeVales=imp1 from tmpVales where cod_cen=@auxcod_Cen
select @importeEfectivo=importe2 from tmpDiarioEfectivo where cod_cen=@auxcod_Cen
select @importeTalones=importe2 from tmpDiarioTalones where cod_cen=@auxcod_cen
select @importeTarjetas1=importe3 from tmpDiarioTarjetas where cod_cen=@auxcod_cen
select @importeTarjetas2=importe1 from tmpDiarioSegundaForma where cod_cen=@auxcod_cen
select @importeGastos=importe2 from tmpDiarioGastosTarjetas where cod_cen=@auxcod_cen
select @importeVales=isnull(@importeVales,0)
select @importeEfectivo=isnull(@importeEfectivo,0)
select @importeTalones=isnull(@importeTalones,0)
select @importeTarjetas1=isnull(@importeTarjetas1,0)
select @importeTarjetas2=isnull(@importeTarjetas2,0)
select @importeGastos=isnull(@importeGastos,0)
print @auxcod_cen
print @importeVales
print @importeEfectivo
print @importeTalones
print @importeTarjetas1
print @importeTarjetas2
print @importeGastos
insert into detallecaja_aux (cod_cen,importe1)
values(@auxcod_cen, @importeVales+@importeEfectivo+@ImporteTalones+@ImporteTarjetas1+@importeTarjetas2-@importeGastos)
fetch next from cursortemporal into @auxcod_cen
select @importeVales=0
select @importeEfectivo=0
select @importeTalones=0
select @importeTarjetas1=0
select @importeTarjetas2=0
select @importeGastos=0
end
close cursortemporal
*/
select * from detallecaja_aux
GO
When I try to run it from visual basic it slow down the sql server.
What can I do?
View 2 Replies
View Related