Writing Query To Dynamically Select A Database Table

Sep 24, 2006

Is there a way I can write a query to dynamically select a database table. That is, instead of having a variable for a certain column like customerId which would be €ścustomerID = @customerID€? I want to use the variable to select the table. I assume I may have to use a stored procedure but I am unclear as to how this would be coded.

Thanks

View 1 Replies


ADVERTISEMENT

Transact SQL :: Dynamically Select Table In Query?

May 18, 2015

How  Can I select  Table Dynamically from in Side SQL Query

i.e.,
Select * from (Here I want Select the Dynamically from other Query)

View 6 Replies View Related

Help Writing A SELECT Query, Please. (Should Be Interesting For You!!!)

May 28, 2008

All- I would greatly appreciate some assistance in creating a SELECT statement for table headcount in the following problem:
First, find the schema here: http://home.pacbell.net/eulimi/schema_headcount.GIF
The problem:
Given a person_id (a record in the person table), list all headcount records WHERE:1) headcount.person_id = person.person_id AND2) the headcount.act_session_id belongs to a activity (from the activity_session table) that the person is allowed to attend by virture of the person's membership in a subexpedition.
Note that:
- A person can be a member of one or more circles (via the circle_person table)- Each circle belongs to exactly one subexpedition.- A persons who is a member of a subexpedition (via one or more circles) is entitled to sign up for one or more activities (activity_sessions) associated with the subexpedition.
So, put yet another way, the SELECT command should show, for a given person_id, the list of records in headcount that includes the activities (act_session_id) that the person is entitled to join by virtue of the persons membership in the subexpedition via his circle. (Whew!)
I hope this is enough information. I think the problem would be fun if I knew what I was doing. (SQL newbie here.) I suspect I need several INNER JOINs and a compound WHERE clause.
Thanks in advance!!!

View 5 Replies View Related

Writing Query Results To New Table

Dec 4, 2000

I have written several scripts to pull in nested info to the analyzer window. How do I get this data to write to the new table I have created in the database? here is the current script:

select Hierarchy_List.Hierarchy_Label as Hierarchy_Name,
Hierarchy_List.hierarchy_ID as Hierarchy_ID,
Hierarchy_List.Parent_ID as Parent_ID,
frequency_item.manufacturer as Motor_Make,
frequency_item.model as Frame
from hierarchy_list full outer join Frequency_item
ON HIERARCHY_LIST.HIERARCHY_ID = frequency_item.HIERARCHY_ID
where parent_id in (select hierarchy_id from hierarchy_list where parent_id in
(select hierarchy_id from hierarchy_list where parent_id in
(select hierarchy_id from hierarchy_list where parent_id in
(select hierarchy_id from hierarchy_list where parent_id=0)
and parent_id<>0) and parent_id<>0) and parent_id<>0)
and parent_id<>0 and frequency_item.description = 'motor'

I need to move this data to the VAER.Al_Machines and the column names are the same. I can move data via DTS, but it won't work on this because the nested info. Is there a script addendum I can add to this to execute both the search and the transfer in one job so I can automate it? Thanks for any help.

Mick Flanigan

View 2 Replies View Related

Want A Stored Procedure To Dynamically Select Views Pulled From A Table.

Feb 1, 2007

I am building a dashboard features that allows user to select reports from a dropdownlist. It is pulling from a table called Reports (cols: ReportID, Description, sqlView) In this Report table the report is associated to a view that queries the report.
And the user's selections are stored in table called UserReport (cols: userID, ReportID, createDt) .
I need to get a Dataset to contain datables of all reports selected. (for example a user select 3 reports, the dataset should contain 3 datables that represent the report).
I want to accomplish this by create a store procedure that queries the Reports table and then dynamically executes the views that related to the user selected reports. Can anyone give me an example on how to create the storeprocedure? 
Thanks,
CG 
 
 
 

View 3 Replies View Related

Writing To A Text File From A Database Query.

Jul 20, 2005

I need to just back one table and not all the data in the table. Is there away to have SQL save the data return from a query to some text file that Ican then use to build the table in another table on another server?I am SQL server 7Thanks,S

View 1 Replies View Related

SQL Server 2014 :: Writing A Cross Join Query With One Table?

Jul 19, 2015

writing a cross join query with one table:

Cities(City_name, X_coordinate, Y_coordinate)

the result should be all combinations without reverse column returns

SELECT * FROM [dbo].[Cities] as P1
Cross JOIN [dbo].[cities] as p2
where (p1.City_name != p2.City_name) and ???

for example if there are three Cities as A,B,C the result should be: A->B, A->C, B->C (without the returns B->A, C->A, C->B)

View 8 Replies View Related

How To Dynamically Assign Database Name In Query Or Store Procedure?

Sep 22, 2006

Hello,

I am not sure if this possible, but I have store procedures that access to multiple databases, therefore I currently have to hardcode my database name in the queries. The problem start when I move my store procedures into the production, and the database name in production is different. I have to go through all my store procedures and rename the DBname. I am just wonder if there is way that I could define my database name as a global variable and then use that variable as my DB name instead of hardcode them?

something like

Declare @MyDatabaseName varchar(30)

set @MyDatabaseName = "MyDB"

SELECT * from MyDatabaseName.dbo.MyTable

Any suggestion? Please.

Thanks in advance

View 8 Replies View Related

Adding A Column To A Table Dynamically Against A Database?

Oct 3, 2007

I have the folowing databases DB1,DB2,DB3,D4,DB5........
I have to loop through each of the databases and find out if the database has a tablename with the word 'Documents'( like 'tbdocuments' or 'tbemployeedocuments' and so on......)
If the tablename having the word 'Documents' is found in that database i have to add a column named 'IsValid varchar(100)' against that table in  that database and there can be more than 1 'Documents' table in a database.
can someone show me the script to do it?
Thanks.
 
 

View 6 Replies View Related

Declaring A Table Variable Within A Select Table Joined To Other Select Tables In Query

Oct 15, 2007

Hello,

I hope someone can answer this, I'm not even sure where to start looking for documentation on this. The SQL query I'm referencing is included at the bottom of this post.

I have a query with 3 select statements joined together like tables. It works great, except for the fact that I need to declare a variable and make it a table within two of those 3. The example is below. You'll see that I have three select statements made into tables A, B, and C, and that table A has a variable @years, which is a table.

This works when I just run table A by itself, but when I execute the entire query, I get an error about the "declare" keyword, and then some other errors near the word "as" and the ")" character. These are some of those errors that I find pretty meaningless that just mean I've really thrown something off.

So, am I not allowed to declare a variable within these SELECT tables that I'm creating and joining?

Thanks in advance,
Andy



Select * from

(

declare @years table (years int);

insert into @years

select

CASE

WHEN month(getdate()) in (1) THEN year(getdate())-1

WHEN month(getdate()) in (2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12) THEN year(getdate())

END

select

u.fullname

, sum(tx.Dm_Time) LastMonthBillhours

, sum(tx.Dm_Time)/((select dm_billabledays from dm_billabledays where Dm_Month = Month(GetDate()))*8) lasmosbillingpercentage

from

Dm_TimeEntry tx

join

systemuserbase u

on

(tx.owninguser = u.systemuserid)

where

Month(tx.Dm_Date) = Month(getdate())-1

and

year(dm_date) = (select years from @years)

and tx.dm_billable = 1

group by u.fullname

) as A

left outer join

(select

u.FullName

, sum(tx.Dm_Time) Billhours

, ((sum(tx.Dm_Time))

/

((day(getdate()) * ((5.0)/(7.0))) * 8)) perc

from

Dm_TimeEntry tx

join

systemuserbase u

on

(tx.owninguser = u.systemuserid)

where

tx.Dm_Billable = '1'

and

month(tx.Dm_Date) = month(GetDate())

and

year(tx.Dm_Date) = year(GetDate())

group by u.fullname) as B

on

A.Fullname = B.Fullname

Left Outer Join

(

select

u.fullname

, sum(tx.Dm_Time) TwomosagoBillhours

, sum(tx.Dm_Time)/((select dm_billabledays from dm_billabledays where Dm_Month = Month(GetDate()))*8) twomosagobillingpercentage

from

Dm_TimeEntry tx

join

systemuserbase u

on

(tx.owninguser = u.systemuserid)

where

Month(tx.Dm_Date) = Month(getdate())-2

group by u.fullname

) as C

on

A.Fullname = C.Fullname

View 1 Replies View Related

SQL Server 2012 :: How To Pull Value Of Query And Not Value Of Variable When Query Using Select Top 1 Value From Table

Jun 26, 2015

how do I get the variables in the cursor, set statement, to NOT update the temp table with the value of the variable ? I want it to pull a date, not the column name stored in the variable...

create table #temptable (columname varchar(150), columnheader varchar(150), earliestdate varchar(120), mostrecentdate varchar(120))
insert into #temptable
SELECT ColumnName, headername, '', '' FROM eddsdbo.[ArtifactViewField] WHERE ItemListType = 'DateTime' AND ArtifactTypeID = 10
--column name
declare @cname varchar(30)

[code]...

View 4 Replies View Related

Need Help W/ Postback To 'Customers' Table On Form Using Select Query From 'Parameters' Table

Dec 20, 2007

I have set up a 'Parameters' table that solely stores all pre-assigned selection values for a webform. I customized a stored query to Select the values from the Parameters table. I set up the webform. The result is that the form1.apsx automatically populates each DropDownList task with the pre-assigned values from the 'Parameters' table (for example, the stored values in the 'Parameters' table 'Home', 'Business', and 'Other'  populate the drop down list for 'Type').
The programming to move the selected data from form1.aspx to a new table in the SQL database perplexes me. If possible, I would like to use the form1.aspx to Postback (or Insert) the "selected" data to a *new* column in a *new* table (such as writing the data to the 'CustomerType' column in the 'Customers' table; I clearly do not want to write back to the 'Parameters' table). Any help to get over this hurdle would be deeply appreciated.

View 1 Replies View Related

Problem With Easy Select And Writing To A Label

Apr 23, 2008

I'm writing my first .NET app, and have a simple page where I set up a connection to my db, query it, and write out a value.  But I get this error, that doesn't give me a very good idea of what I should fix...  Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.Source Error:



Line 10: Dim comm As SqlCommand
Line 11: Dim reader As SqlDataReader
Line 12: Dim connectionString As String = ConfigurationManager.ConnectionStrings("IntegratedData").ConnectionString
Line 13:
Line 14: conn = New SqlConnection(connectionString)
   Here's the vb.net code from my page.  It seems soo simple, but I'm missing something.   <%@ Page Language="VB" %>
<%@ Import Namespace="System.Data.SqlClient" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
Dim conn As SqlConnectionDim comm As SqlCommand
Dim reader As SqlDataReaderDim connectionString As String = ConfigurationManager.ConnectionStrings("IntegratedData").ConnectionString
 conn = New SqlConnection(connectionString)
 comm = New SqlCommand("Select tkinit, tklast as FullName from tEliteTimeKeep", conn)
conn.Open()
 
reader = comm.ExecuteReader()employeesLabel.Text = reader.Item("tklast")
 
reader.Close()
conn.Close()
 End Sub
</script><html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server"><title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
 
<asp:Label ID="EmployeesLabel" runat="server" ></asp:Label>
 
</div></form>
</body>
</html>

View 5 Replies View Related

Dynamically Select Column

Sep 29, 2004

Hey all. I'm trying to create a stored proc that will update a variable column, depending on the parameter I pass it. Here's the stored proc:


CREATE PROCEDURE VoteStoredProc
(
@PlayerID int,
@VoteID int,
@BootNumber nvarchar(50)
)
AS

DECLARE @SQLStatement varchar(255)
SET @SQLStatement = 'UPDATE myTable SET '+ @BootNumber+'='+ @VoteID + ' WHERE (PlayerID = '+ @PlayerID +')'

EXEC(@SQLStatement)

GO


I get the following error:

Syntax error converting the nvarchar value 'UPDATE myTable SET Boot3=' to a column of data type int


The update statement is good, because if I use the stored proc below (hard-coded the column), it works fine.

CREATE PROCEDURE VoteStoredProc
(
@PlayerID int,
@VoteID int,
@BootNumber nvarchar(50)
)
AS

UPDATE
myTable
SET
Boot3 = @VoteID
WHERE
PlayerID = @PlayerID
GO


Is there a way to dynamically choose a column/field to select from? Or is my syntax incorrect..?
Thanks!

View 2 Replies View Related

How To -- Select * Into Tab_mmddyyyy From Tab Dynamically?

Jan 11, 2008

How to -- select * into tab_mmddyyyy from tab dynamically?

View 1 Replies View Related

How Do I Dynamically Change The TOP X Portion Of A SELECT

Oct 26, 2006

I'm sure I'm missing something. I am returning the TOP X number of customers by revenue and I'd like to change the number of records returned by passing a parameter but I keep getting an error.    @TopX int ( or varchar)    SELECT @TopX  CompanyName, Amount FROM Sales Where..... Why will this not work?

View 4 Replies View Related

Dynamically Select Rows From Last Month

Nov 9, 2014

This is my Statement.

SELECT a.FIRMA,
a.PSNR,
a.FELDNR,
a.PFLFDNR,
a.INHALT AS Cardnr,
a.PFGLTAB,

[Code] .....

But it deliver me also rows which are not in valid. I need only rows from last month from 01.10 until 31.10 and this rows are over the time. How can i select dynamically all row between 01.10 and 31.10 ?

FIRMAPSNRFELDNRPFLFDNRCardnrPFGLTAB PFGLTBISKSTNRPSPERSNRPSVORNAPSNACHNA
13980211DU9572014111220321231000043000957xxxxx xxxxxx
13990211DU9552014110120321231000010000955xxxxx xxxx
14030211DU9602014120120321231000086000960xxxxxxxxx

View 10 Replies View Related

Transact SQL :: Adding Results Of Query To Another Query Via Dynamically Added Columns

Jul 30, 2015

For each customer, I want to add all of their telephone numbers to a different column. That is, multiple columns (depending on the number of telephone numbers) for each customer/row. How can I achieve that?

I want my output to be

CUSTOMER ID, FIRST NAME, LAST NAME, TEL1, TEL2, TEL3, ... etc

Each 'Tel' will relate to a one or more records in the PHONES table that is linked back to the customer.

I want to do it using SELECT. Is it possible?

View 13 Replies View Related

How Can I Dynamically Build Sql SELECT Using ASP 1.0 Array Concept

Jun 6, 2007

The below code is ASP 1.0 to dynamically search a database and I want to use the same concept for a ASP.Net 2.0 solution.  Do I do this in the code behind or on the aspx page and if on the aspx page what controls do I use for the array split?  Basically where do I start.  It took me a long time to get this old code working, I am hoping it is simpler in 2.0.
Thank you
OLD ASP 1.0 code to dynamically build a Sql Select statement for searching a database using one or more search words entered by user.
If Request.Querystring("kwdSearch") <> "" ThenDim kwdString, ArrKwdString, iCountiCount = 0 kwdString = Replace(Request.Querystring("kwdSearch"), "'", "''")ArrKwdString = Trim(kwdString)ArrKwdString = Split(kwdString, " ",-1,1) For iCount = 0 to UBound(ArrKwdString) If iCount < UBound(ArrKwdString) Then  Criteria = Criteria & "tblLinkInfo.L_Keywords LIKE '%" & ArrKwdString(iCount) & "%' AND "  Else  Criteria = Criteria & "tblLinkInfo.L_Keywords LIKE '%" & ArrKwdString(iCount) & "%' " End ifNext    RS.Open "SELECT * FROM tblLinkInfo Where (" & Criteria & ") AND L_Enabled = 1 ORDER BY " & SortBy & "L_Rank", CNN, 3 If RS.EOF Then  If Rs.State Then RS.Close  RS.Open "SELECT * FROM tblLinkInfo WHERE L_Description LIKE '%" & Replace(Request.Querystring("kwdSearch"),"''","'") & "%' AND  L_Enabled = 1  ORDER BY " & SortBy & "L_Rank", CNN, 3  End If
  RESULTS --- Display results with Repeater1.DataBind(); etc
  Exit SubEnd If

View 3 Replies View Related

Dynamically Adding Select Parameters (Filter)

Jul 24, 2007

how do i add parameters like this dynamically? do i need to change the select command? to add the @ID part? 

View 4 Replies View Related

Dynamically Assign Select Statement To SqlDataSource

Jan 31, 2008

I wish to dynamically assign Select Statement to SqlDataSource. Anyone has any idea?? Is it possiable at all?
I am coding using C# under Framwork 2.0

View 1 Replies View Related

Dynamically Assign Select Statement To SqlDataSource

Jun 16, 2008

How can i assign select statement to a sqldatasource
I mean if the user clicks button 1
sqldatasource=-"select * from customers where status='ClOSED'  "
or else if the user clicks button2
 sqldatasource="Select * from Customers Where Status='OPEN'  "
 I want to bind the sqldatasource to a gridview finally .
 Is this possible ?
I tried sqldatasource filters  But am reallly confused
Any suggestions/solutions are appreciated
thankyou

View 8 Replies View Related

SELECT - Dynamically Determine Fields To Return

Dec 6, 2004

Hello,

I m writing a stored procedure to query a table Population that has the following fields - CityId, CityName, Plus0, Plus10, Plus20, Plus30, Plus40, Plus50, Plus60, Plus70, Plus80. The field Plus0 contains the number of people of age > 0 living in the city, Plus10 contains the number of people of age > 10 living in the city and so on. Given the city id and age groups like 20To40, 50To60, 40Plus, etc., I should be able to query the number of people in the city corresponding to the requested age group. Note that if the requested age group was 20To60, I need to make use of only 2 fields Plus20 and Plus60 in the table to compute this value. And if the requested age group was 40Plus, then I need only the value in the field Plus40. The problem is that a wide variety of age groups can be requested like 0Plus, 10Plus, ... , 80Plus, 0To10, 0To20, 0To30, .... 70To80.

Which is the most effecient way to handle this ?

1. Have a stored procedure that returns all the fields even though only 1 or 2 of them would be actually used ?

In this case, if I returned data for a large number of cities then there would be a lot of unnecessary information that was returned by the query. Lots of data would be passed through the network though most of it would not be used.

2. Have a stored procedure that takes in parameters @Plus0, @Plus10, @Plus20, .. @Plus80 that are bits indicating whether the field was required or not and then using a CASE statement to return values for a field only if the corresponding bit parameter was set, and returning NULL if the corresponding bit paramter was not set ?

In this case, I would be returning NULL for all those fields that were not required for a particular age group. This would save some network bandwidth, wouldn't it ?

3. Pass in the age group itself (ex: 0To20) as a parameter to the stored procedure and have lots of IF statements, one for each age group, that return only the fields that are needed for that age group.

This leads to a lot of code repitition.

4. Use a similar approach as above but use dynamic SQL queries to avoid code repitition.

But using dynamic SQL queries can affect the performance of the stored procedure as they need to be compiled each time.

5. Any other possible approaches ??

Looking forward to your responses,

Thanks much,

bmgun.

View 3 Replies View Related

Does Reporting Services Allow You To Select A Dataset Dynamically?

Apr 30, 2007

I have a remote report ...
I need to call one of two stored procedures depending on which parameters were passed to the report. (Both stored procedures return the same fields.)
Does SQL Reporting Services allow you to switch the dataset or stored procedure name dynamically? If so, where do I put the logic? Right now I have it working with one stored procedure.
I'm thinking that I should just make one stored procedure that takes all parameters and calls one of the other two stored procedures. Do I have any options besides this?

Thanks in advance!

View 3 Replies View Related

Need Help On Writing A Query

Jan 22, 2008

Hello, I have two tables: Customer Training Requests has say two columns.Customer    -   Class Requested a                        1b                        1c                        1a                        2b                        2c                        3a                        3 I have another table called packages, which has packages of class.Package No.        Class1                            11                            2 I want to write a query which will return only those customers who have requested exactly the classes in a particular package.so in above example if the package is 1 the query should return only customer b as only customer b has requested class 1 and 2. Any suggestions? Thanks,Paresh.     

View 8 Replies View Related

Help Writing Sql Query

Feb 23, 2008

Hello, how can do the following using sql:
 if exists(select * from siteindex where site_url like '%msn.com')ThenUpdate siteindex Set dmodified = GetDate(), isFullPage = 0, fp_flname = 'filename', fp_iWidth = 800, fp_iheight = 600
Where site_url = '%msn.com'
else
insert into siteindex (site_url, dcreated, dmodified, isFullPage, fp_flname, fp_iWidth, fp_iHeight)
Values ('msn.com', GetDate(), GetDate(), 0, 'filename', 800, 600)
 I cant get the syntax right.  Thanks!

View 1 Replies View Related

Sql Query Writing

Apr 28, 2008

Hi all,
        I have a problem with retrieving data from lookup tables. Ok here is the issue I have a Tables ... 
Tables  |     Schools                                      StuAccount
Fields   |     Sch_Id (pk)                                 Student_ID (pk)
                  School_Name                             AccountableSch_Id
                   DistrictName                             TestedSch_Id
                                                                    ParticipatedSch_Id
Ok, so i have two tables Schools and StuAccount, each has one primary key and and the StuAccount has three foreign keys that associates to the Schools TABLE which has a the definition of school names wich i want to retrieve for all three foreign key in the stuaccount table. Here is what i want ....
Student_ID 
AccountableSch_Id 
Shool_Name( this the name of the AccountableSch_Id )
TestedSch_Id
Shool_Name( this the name of the TestedSch_Id)
ParticipatedSch_Id
Shool_Name( this the name of the  ParticipatedSch_Id)
 I just want to look up the id and put the school name in the final resulting join and i have no idea how to lookup the table School three time and put school name for all three foreign keys.??
Any help will be much appreciated.
Thanks
 

View 4 Replies View Related

Please Help Me In Writing A Query

Apr 5, 2006

I have table Products
I have coloumn like ProductName:
ProductName Having two values like Colgate and pepsi

I want to change these coloumn values in the result set
Please write a query

Hi here is clear question?

Table Name is Products
in that One coloumn name is
ProductsName:
and the values for productsName are
colgate
pepsi

the result set should be like following way

ProductsName:
Mike
Johnson

so here I am replacing value Mike instead of colgate
and Johnson instead of pepsi

View 1 Replies View Related

Help With Writing Query

Apr 14, 2006

Please help with writing query
I have 2 tables:
Table1:
IDDescription
1name1
2name2
3name3...

Table2:
SiDID
1231
4562
789myname
852yourname

if description exisits in table1 get description from table1 in
all other cases get ID from table2

View 5 Replies View Related

Help Writing Query

Apr 19, 2006

please help me write a query:
I have a user function dbo.udf_Valid which is return true or false
(@SID ,@PType,@Group,@Date)

Table 1 with this info:
SID PType Group
12 12 123
45 1 456

Table2 with this info:
PType PType2
12 13
12 45
12 8
1 8
1 9

when I pass the data from table1 to the function I am Okay.
The complexity starts when table2 is involved.
I need to pass PType2 to the function if Ptype is exists in table1.
If function returns true for one of the PType2 return true in all other cases false.

View 3 Replies View Related

Need Help Writing A Query

Aug 8, 2005

I need assistance on writing a particular query:

I need to be able to filter out duplicates that have different values in a particular field.

For example, I have a table that contains the following:


Code:


WBS1 WBS2 WBS3 Amount Section
123 13 00 475 F
123 13 00 0 L
123 21 01 125 C
123 24 03 50 L



I need to filter out the first two lines because they have the same values for the first three columns but the last column under 'Section' has different values.

Can someone help me?

Thanks

View 2 Replies View Related

Writing A Query

Apr 28, 2006

Hello I'm new on sql server and I wonder if there's an specific order for writing a query's clauses (joins, and other conditions in where clause or even the order of the tables in the from clause), I mean, I have a query that takes 1 minute executing, but if I execute the same query after moving the tables in the from clause (changing the order) It takes 5 seconds, could you please tell me Why ??? and what's the best order from writing a query ?


This is the query I was talking about:


SELECT TREP_VALOR_PRECIOS.CDPRECIO,
TREP_VALOR_PRECIOS.NMANO,
TREP_VALOR_PRECIOS.NMSEMANA,
ISNULL(DBO.FNCREP_VALORPRECIO(TREP_PRECIOS.CDPRECI O,0,TREP_VALOR_PRECIOS.NMSEMANA,TREP_VALOR_PRECIOS .NMANO),0) VRPAGO_COBRO,
UN_TASASCAMBI.TASTASACAMB VRTASA_CAMBIO,
TREP_PRECIOS.CDTIPO_PRECIO,
TREP_VALOR_PRECIOS.SNACTIVO,
'N' SNACTIVAR
FROM
UN_TASASCAMBI, -- I just moved this one to the end of the from clause
T2_CALENDARIO, -- I just moved this one to the end of the from clause
UN_MONEDEXTRA,
TREP_PRECIOS TREP_PRECIOS_BASE,
TREP_VALOR_PRECIOS,
TREP_PRECIOS
WHERE T2_CALENDARIO.CALFECHAINICIAL BETWEEN UN_TASASCAMBI.TASFECHDESD AND UN_TASASCAMBI.TASFECHHAST
AND UN_TASASCAMBI.TASCOMPANIA = UN_MONEDEXTRA.MEXCOMPANIA
AND UN_TASASCAMBI.TASMONECAMB = UN_MONEDEXTRA.MEXCODIGO
AND T2_CALENDARIO.CALSEMANA = TREP_VALOR_PRECIOS.NMSEMANA
AND T2_CALENDARIO.CALANO = TREP_VALOR_PRECIOS.NMANO
AND T2_CALENDARIO.CALTIPOFRUTA = '01'
AND UN_MONEDEXTRA.MEXCOMPANIA = TREP_PRECIOS_BASE.CDCOMPANIA
AND UN_MONEDEXTRA.MEXCODIGO = TREP_PRECIOS_BASE.CDMONEDA
AND TREP_PRECIOS_BASE.CDMONEDA <> 'PESOC'
AND TREP_PRECIOS_BASE.CDPRECIO = TREP_VALOR_PRECIOS.CDPRECIO
AND TREP_VALOR_PRECIOS.SNACTIVO = 'S'
AND TREP_VALOR_PRECIOS.CDPRECIO = DBO.FNCREP_OBTENER_PRECIO_BASE(TREP_PRECIOS.CDPREC IO)
AND TREP_PRECIOS.CDTIPO_PRECIO = 'F'

View 7 Replies View Related

Need Help Writing A Query...

Apr 15, 2008

Hi Friends,

I need help on writing an optimized query for the following problem..

Consider a table with columns "Date Emp1 Emp2"

Date Emp1 Emp2
1-feb 1 . . 2
2-feb 3 . . 4
3-feb 6 . . 1
4-feb 1 . . 2
5-feb 1 . . 5
6-Feb 5 . . 7


Now, I want search for records with employee id 1 in a way that if column emp1 contains 1 then I want the data in column emp2, and if column emp2 contains 1, then I want data in column emp1.

The output has to be a single column with no duplicate values. In the above example, for employee id 1, the output would be, 2,5 and 6 only.

This table has lakhs of records. I have to scan both columns for a given employee id. What will be the most optimized way to retrieve the data faster. Also, do I need to restructure this table for faster data retrieval?
I have indexes on emp1 and emp2 columns. Do we need union here and if yes, what is the best optimized query for the same?

View 9 Replies View Related







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