How To Build FROM Clause Dynamically

Mar 29, 2004

I look trough the forum, but did not find any simular problem. Somebody, help, please!
What I need to do is to write an algorithm which create a FROM clause for SQL query, using tables and joined fields, specified by the user. There could be up to 25 tables with any type of join (INNER, OUTER, FULL, CROSS). I know the basic structure of the FROM clause: "from T1 inner(or other type) join T2 on T1.field=T2.field" etc., but the main problem that users can specify tables in any order and I have to re-arrange them to create valid statement.

View 10 Replies


ADVERTISEMENT

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

Build WHERE Clause

Apr 8, 2008

I have a stored procedure which expects one parameter @City

Let’s say @City holds pipe delimited value: "New York|London|Paris"

In my stored procedure I need to replace all pipes with OR operator? In other words my select statement needs to look like this :

SELECT * FROM City WHERE CityName= 'New York' OR CityName= 'London' OR CityName= 'Paris'

Thank you

View 7 Replies View Related

Build Dynamic WHERE Clause

Apr 14, 2008

I have a stored procedure which expects one parameter @Company
The variable @Company holds pipe delimited value: "CNN|AOL|ABC"

I need to build a WHERE clause by parsing @Company value, so the select will look like below:

SELECT *
FROM Company
WHERE CompanyID IN (SELECT DISTINCT(CompanyID) FROM v_Company WHERE CompanyName = 'CNN')
AND CompanyID IN (SELECT DISTINCT(CompanyID) FROM v_Company WHERE CompanyName = 'AOL')
AND CompanyID IN (SELECT DISTINCT(CompanyID) FROM v_Company WHERE CompanyName = 'ABC')

Thanks for your help

View 2 Replies View Related

Build Dynamic WHERE Clause

Apr 14, 2008

Hello,

I have a stored procedure which expects one parameter @Company
The variable @Company holds pipe delimited value: "CNN|AOL|ABC"

I need to build a WHERE clause by parsing @Company value, so the select will look like below:

SELECT *
FROM Company
WHERE CompanyName = 'CNN'
AND CompanyName = 'AOL'
AND CompanyName = 'ABC'


P.S I know that above select doesn€™t really make sense , but I have a bigger query that would be hard to explain in this topic so I just simplified it.

Thank you

View 8 Replies View Related

Transact SQL :: How To Build Dynamic WHERE Clause In Openquery To Linked Database

Jul 17, 2015

I'd like to modify the dates within this where clause to be dynamic, building the date depending on the current year, but everything I try doesn't seem to be syntactically correct.

SELECT *
FROM Openquery(LS_CIS, 'select * from BI_WRKFLW_TASKS where (BI_EVENT_DT_TM>=''1/1/2011'' and (BI_NEEDED_DT_TM>=''1/1/2011''))OR (BI_EVENT_DT_TM>=''1/1/2011'' and BI_NEEDED_DT_TM is null)') AS derivedtbl_1
I'd like to replace ''1/1/2011''  in the where clause with something like:
CAST(CAST(YEAR (GETDATE())-4 AS varchar) + '-' + CAST(01 AS varchar) + '-' + CAST(01 AS varchar) AS DATETIME)

View 9 Replies View Related

Dynamically Decide The Conditions In The 'WHERE' Clause

Apr 1, 2008


I have a report and in it there is a dataset that of course contains a query.
I want the query conditions to be changed automatically (the 'WHERE' clause) according to the environment it runs on, so if I put the same report on different customer computers, it will act differently according to the relevant 'WHERE' clause conditions.
Is it possible to use a parameter or "solution configurations" (or something else) in order to decide the conditions in the 'WHERE' clause?
Help will be really appreciated.
Thanks in advance.

View 1 Replies View Related

Dynamically Inserting A List In WHERE Clause Of A Query

Jul 8, 2014

What I need?: A way of dynamically inserting a list in the WHERE clause of a query. (in the form, WHERE ID = 1,2,3,6,9 etc)

Imagine an example DB with 3 columns Student ID, Name, Teacher_ID. (Lets assume Teacher_ID with value 100 means its the Headmaster)

I need to create a list with Student ID's, who are directly/indirectly under the Headmaster. Example:

Headmaster
Teacher 1 (ID 200)
Teacher 2 (ID 250)
Student 1 (ID 300)
Director
Teacher 4
Student 5

In the above example, since I only want those students/teachers under the headmaster, either directly/indirectly, my list would contain Teacher 1, Teacher 2, and Student 1. (In my case, just their ID's, so 200, 250, 300)

Director, Teacher 4 and Teacher 5 wouldnt be in the list since theyre not directly/indirectly Headmaster.

View 2 Replies View Related

Dynamically Populating An IN() Clause Within An SSIS Package.

May 9, 2007

Hi,



I currently have a list of User IDs (in a flat file) and I need to connect to a database I have read-only access to, so that I can retrieve additional data about these users.



I imagined a package that ran a query something like:

SELECT * FROM table WHERE UserID IN (<dynamically populated from flat file>).



Can somebody give me some advice as to how I can achieve this (either the way I suggested or another way).



Kind Regards,



Adam.

View 11 Replies View Related

Building Where Clause Dynamically In Stored Procedure

Feb 8, 2008



Hello All,

I have created SP in SQL 2K5 and make the where clause as parameter in the Sp. i am passing the where clause from my UI(ie ASP.NET), when i pass the where clause to SP i am not able to fetch the results as per the given criteria.

WhereClause from UI: whereClause="where DefectImpact='High'"

SQL Query in SP: SELECT @sql='select * from tablename'

Exec(@sql + @whereClause )


Here i am not able to get the results based on the search criteria. Instead i am getting all the results.

Please help me in this regard.

Thanks,
Subba Rao.

View 11 Replies View Related

T-SQL (SS2K8) :: Change Set Clause Of Update Statement Dynamically Based On Some Condition

May 27, 2015

I want to change Set clause of Update Statement dynamically based on some condition.

Basically i have 2 Update statments having same FROM clause and same JOIN clause.

Only diff is SET clause and 1 Where condition.

So i am trying to combine 2 Update statements into 1 and trying to avoid visit to same table twice.

Update t
Set CASE **WHEN Isnull(td.IsPosted, 0) = 0
THEN t.AODYD = td.ODYD**
*ELSE t.DAODYD = td.ODYD*
END
From #ReportData As t
Join @CIR AS tmp On t.RowId = tmp.Max_RowId

[Code] ....

But CASE statement is not working...

View 7 Replies View Related

Error On Build Solution, If SSIS Project Is Part Of Build

Mar 22, 2006

Hello,

we have automated build on every night. In our solution is SSIS project, where each package is encrypted per password. We call build process per command line like this..

C:ProgrammeMicrosoft Visual Studio 8Common7IDEdevenv.exe (c:DevelopmentX3\X3.sln /build Release)' in 'c:DevelopmentProjectsDailyBuild

Through build process we get a error:


External Program Failed: C:ProgrammeMicrosoft Visual Studio 8Common7IDEdevenv.exe (return code was 1):

We think a reason is, that on build of SSIS project must be entered a password. You can wonder for what we need that SSIS packages are part of our build. We hope that on build process is also created Deployment Utility, if so set in dtproject.user. Is it so? Is there any way to create Deployment utility on automated build process? Can be a password provided pre command line?

with best regards

Anton Kalcik

View 5 Replies View Related

Transact SQL :: How To Create UNION Clause With Two Queries That BOTH Have WHERE Clause

Nov 4, 2015

I have a quite big SQL query which would be nice to be used using UNION betweern two Select and Where clauses. I noticed that if both Select clauses have Where part between UNION other is ignored. How can I prevent this?

I found a article in StackOverflow saying that if UNION has e.g. two Selects with Where conditions other one will not work. [URL] ....

I have installed SQL Server 2014 and I tried to use tricks mentioned in StackOverflow's article but couldn't succeeded.

Any example how to write two Selects with own Where clauses and those Selects are joined with UNION?

View 13 Replies View Related

GROUP By Clause Or DISTINCT Clause

Jul 23, 2005

Hi, can anyone shed some light on this issue?SELECT Status from lupStatuswith a normal query it returns the correct recordcountSELECT Status from lupStatus GROUP BY Statusbut with a GROUP By clause or DISTINCT clause it return the recordcount= -1

View 3 Replies View Related

Filtering Results In The Where Clause Vs A Having Clause

Oct 25, 2007

I am working with a vendor on upgrading their application from SQL2K to SQL2K5 and am running into the following.

When on SQL Server 2000 the following statement ran without issue:

UPDATE dbo.Track_ID

SET dbo.Track_ID.Processed = 4 --Regular 1 leg call thats been completed

WHERE Processed = 0 AND LegNum = 1

AND TrackID IN

(


SELECT TrackID

FROM dbo.Track_ID

GROUP BY TrackID

HAVING MAX(LegNum) = 1 AND


TrackID + 'x1' IN


(


SELECT

dbo.Track_ID.TrackID + 'x' + CONVERT(NVARCHAR(2), COUNT(dbo.Track_ID.TrackID))

FROM dbo.Track_ID INNER JOIN dbo.transactions


ON dbo.Track_ID.SM_ID = dbo.transactions.sm_session_id

GROUP BY dbo.Track_ID.TrackID

)

)
Once moved to SQL Server 2005 the statement would not return and showed SOS_SCHEDULER_YIELD to be the waittype when executed. This machine is SP1 and needs to be upgraded to SP2, something that is not going to happen near time.

I changed the SQL to the following, SQL Server now runs it in under a second, but now the app is not functioning correctly. Are the above and the following semantically the same?


UPDATE dbo.Track_ID

SET dbo.Track_ID.Processed = 4 --Regular 1 leg call thats been completed

WHERE Processed = 0 AND LegNum = 1

AND TrackID IN
(



SELECT TrackID

FROM dbo.Track_ID

WHERE TrackID + 'x1' IN


(


SELECT dbo.Track_ID.TrackID + 'x' + CONVERT(NVARCHAR(2), COUNT(dbo.Track_ID.TrackID))

FROM dbo.Track_ID INNER JOIN dbo.transactions


ON dbo.Track_ID.SM_ID = dbo.transactions.sm_session_id

GROUP BY dbo.Track_ID.TrackID

)
GROUP BY TrackID

HAVING MAX(LegNum) = 1

)

View 3 Replies View Related

Expression Defined In SELECT Clause Overwrites Column Defined In FROM Clause

May 14, 2008

2 examples:

1) Rows ordered using textual id rather than numeric id


Code Snippet
select
cast(v.id as nvarchar(2)) id
from
(
select 1 id
union select 2 id
union select 11 id
) v
order by
v.id






Result set is ordered as: 1, 11, 2
I expect: 1,2,11


if renamed or removed alias for "cast(v.id as nvarchar(2))" expression then all works fine.

2) SQL server reject query below with next message

Server: Msg 169, Level 15, State 3, Line 16
A column has been specified more than once in the order by list. Columns in the order by list must be unique.




Code Snippet
select
cast(v.id as nvarchar(2)) id
from
(
select 1 id
union select 2 id
union select 11 id
) v
cross join (
select 1 id
union select 2 id
union select 11 id
) u
order by
v.id
,u.id




Again, if renamed or removed alias for "cast(v.id as nvarchar(2))" expression then all works fine.

It reproducible on

Microsoft SQL Server 2000 - 8.00.2039 (Intel X86) May 3 2005 23:18:38 Copyright (c) 1988-2003 Microsoft Corporation Developer Edition on Windows NT 5.1 (Build 2600: Service Pack 2)


and


Microsoft SQL Server 2005 - 9.00.3042.00 (Intel X86) Feb 9 2007 22:47:07 Copyright (c) 1988-2005 Microsoft Corporation Developer Edition on Windows NT 5.1 (Build 2600: Service Pack 2)

In both cases database collation is SQL_Latin1_General_CP1251_CS_AS

If I check quieries above on database with SQL_Latin1_General_CP1_CI_AS collation then it works fine again.

Could someone clarify - is it bug or expected behaviour?

View 12 Replies View Related

ERROR [42000] [Lotus][ODBC Lotus Notes]Table Reference Has To Be A Table Name Or An Outer Join Escape Clause In A FROM Clause

May 27, 2008

I am using web developer 2008, while connecting to I wanted to fetch data from Lotus notes database file, for this i used notesql connector, while connectiong to notes database i am fetting error


ERROR [42000] [Lotus][ODBC Lotus Notes]Table reference has to be a table name or an outer join escape clause in a FROM clause


I have already checked that database & table name are correct, please help me out
How i can fetch the lotus notes data in my asp.net pages.

View 1 Replies View Related

ERROR [42000] [Lotus][ODBC Lotus Notes]Table Reference Has To Be A Table Name Or An Outer Join Escape Clause In A FROM Clause

May 27, 2008

I am using web developer 2008, while connecting to I wanted to fetch data from Lotus notes database file, for this i used notesql connector, while connectiong to notes database i am fetting error


ERROR [42000] [Lotus][ODBC Lotus Notes]Table reference has to be a table name or an outer join escape clause in a FROM clause


I have already checked that database & table name are correct, please help me out
How i can fetch the lotus notes data in my asp.net pages.

View 1 Replies View Related

What Build Is This?

Jan 12, 2001

Hey folks, I just inherited a machine where select @@version returns this:

Microsoft SQL Server 7.00 - 7.00.710 (Intel X86)

Okay, I know that:

623 is orig sql
699 is sp 1
842 is sp 2
961 is sp 3 -- but what's 710 ?

going to http://search.support.microsoft.com/kb/c.asp?ln=en-us gets me exactly 0 <zero> hits. Is this a hotfix someone's aware of?

Any thoughts/documentation/whatever would be appreciated.

Thanks,

Tom

View 1 Replies View Related

SQL To Build SQL

Nov 14, 2000

I know how to use sql to write a block of sql statements by cutting and pasting the results in to the execution window. Now my question is this...
is there a way to create the sql and execute the results. i.e. Automatically cut and paste the results into the execution window and run it??
Something to munch on if your bored. Ideas appreciated.

View 2 Replies View Related

RS Build

Feb 28, 2008

The common way that we use to delpoy reports in production server is using rsbuild.config file and running the command to execute it. Is this a Microsoft product ? does it have any licensing issue if i need to use this approach in my production environment to deploy the reports?

View 1 Replies View Related

Having Clause Without GROUP BY Clause?

Nov 20, 2004

Hi,

What is HAVING clause equivalent in the following oracle query, without the combination of "GROUP BY" clause ?

eg :

SELECT SUM(col1) from test HAVING col2 < 5

SELECT SUM(col1) from test WHERE x=y AND HAVING col2 < 5

I want the equivalent query in MSSQLServer for the above Oracle query.

Also, does the aggregate function in Select column(here the SUM(col1)) affect in anyway the presence of HAVING clause?.

Thanks,
Gopi.

View 3 Replies View Related

Top Clause With GROUP BY Clause

Apr 3, 2008

How Can I use Top Clause with GROUP BY clause?

Here is my simple problem.

I have two tables

Categories
Products

I want to know Top 5 Products in CategoryID 1,2,3,4,5

Resultset should contain 25 Rows ( 5 top products from each category )

I hope someone will help me soon.
Its urngent


thanks in advance

regards
Waqas

View 10 Replies View Related

Diff In On Clause And Where Clause?????

Apr 4, 2007

hi..
i have basic question like

what is differance between conditions put in ON clause and in WHERE clause in JOINS????

see conditions that shown in brown color

select d1.SourceID, d1.PID, d1.SummaryID, d1.EffectiveDate,
d1.Audit, d1.ExpirationDate, d1.Indicator
from[DB1].[dbo].[Implicit] d1 inner join [DB2].[dbo].[Implicit] d2
on d1.SummaryID=d2.SummaryID
AND d1.ListType = d2.ListType
AND (d1.EffectiveDate <= d2.ExpirationDate or d2.ExpirationDate is null)
AND (d1.ExpirationDate >= d2.EffectiveDate or d1.ExpirationDate is null)
whered1.ImplicitID >= d2.ImplicitID AND
(d1.SourceID<>d2.SourceID
OR (d1.SourceID IS NULL AND d2.SourceID IS NOT NULL)
OR (d1.SourceID IS NOT NULL AND d2.SourceID IS NULL)
)


select d1.SourceID, d1.PID, d1.SummaryID, d1.EffectiveDate,
d1.Audit, d1.ExpirationDate, d1.Indicator
from[DB1].[dbo].[Implicit] d1 inner join [DB2].[dbo].[Implicit] d2
on d1.SummaryID=d2.SummaryID
AND d1.ImplicitID = d1.ImplicitIDAND d1.ListType = d2.ListType
AND (d1.EffectiveDate <= d2.ExpirationDate or d2.ExpirationDate is null)
AND (d1.ExpirationDate >= d2.EffectiveDate or d1.ExpirationDate is null)
whered1.ImplicitID >= d2.ImplicitID AND
(d1.SourceID<>d2.SourceID
OR (d1.SourceID IS NULL AND d2.SourceID IS NOT NULL)
OR (d1.SourceID IS NOT NULL AND d2.SourceID IS NULL)
)

another thing...

if we put AND d1.ImplicitID = d1.ImplicitID condition in second query then shall we remove
d1.ImplicitID >= d2.ImplicitID from WHERE clause????

View 6 Replies View Related

SQL Inner Join Clause And The Where Clause

Jan 21, 2008

Hi everyone,
I saw some queries where SQL inner join clause and the where clause is used at the same time. I knew that "on" is used instead of the "where" clause. Would anyone please exaplin me why both "where" and "on" clause is used in some sql Select queries ?

Thanks

View 6 Replies View Related

I Need Help To Build This Query.

Jun 10, 2008

Hi,
    I have two tables called Actcodes and a another table called FundBalances...
 
The Act codes have the following format..
 
PlanId int,
ClientId int,
 StartDate datetime,
EndDate datetime,
ClientActCode char(2)
CodeDescription char(15)
so based on what the user has selected i am getting the names of each codes
 
and they have the following Rows.
PlanId         ClientId           Startdate     EndDate  ClientActCode     CodeDescription
111               1                   1/1/2008      3/31/2008     01                    Begininng balance
111               1                   1/1/2008       3/31/2008     02                   Contributions 
111               1                   1/1/2008      3/31/2008     03                   something
111               1                   1/1/2008       3/31/2008     04                   sdkfjdkf
111               1                   1/1/2008      3/31/2008     05                    dfdfd
111               1                   1/1/2008       3/31/2008     06                  dfddfs 
111               1                   1/1/2008      3/31/2008     09                  dfdf
111               1                   1/1/2008       3/31/2008     15                   dfdkfdlfk
 
and my fund balance i have the following rows..
PlanId int
Participantid int
StartDAte datetime,
end date datetime,
FundId int
Loans
Act1 char(2)
TotAct1 money
.
Act20 char(2)
TotAct20 money
and the data is as follows
PlanId   ParticipantId StartDate EndDate fundId Loans Act1 TotAct1 Act2 totact2 ----- Act20 TotAct20
111         1212           1/1/2008  3/31/2008  15   NULL   01    15.15    02    15.48           20    12.4561
111          1212           1/1/2008 3/31/2008   45   0        01        45.12 02    453.123      20          54.00
so on and so so forth
 
tht Act1 matches the ClientActCode in the Act..
So is there a way i can get those column in my select which have actCodes present in the Act code table. for in... in my act code table for this plan i have 01,02,03,04,05,06, 09, 15 clientAct codes
 
so can i get the its respective Acts and Totacts column as  Act1, Act, Act3, Act Act5, Act6 based on the ClientAct codes.
 
Any help will be appreciated..
Thanks
Karen

View 23 Replies View Related

How To Build My SQL Querry.

Nov 12, 2003

Hi.
I know this querry:

"SELECT TOP 10 * FROM MyTable ORDERBY ..."

will give the top 10 rows.

But how can I build a querry that can get the rows from 40-50 (ie).
Thanks.

View 2 Replies View Related

How To Build This Query

Mar 8, 2004

Hi,
Please Help me to build this query.

I have got a "User" Table
---------------------
UserID UserName
---------------------

1 Tuffy


Another Table "Groups" Table
---------------------
GroupID GroupName
---------------------
1 Manager
2 Employee
3 Sales

I have got a "UserGroup" Table HOLDING ID'S as Foreign key.
The data in the TABLE is like this

---------------------
UserID GroupID
---------------------
1 1(Manager from "Group" Table
1 2(Employee)
1 3(Sales)
2 2(Employee)
2 3(Sales)
---------------------

Now when a user logged in The Groups have to be returned as a string that contains pipe separated Group names
for example "Manager|Employee|Sales|"

So if User 1 log in I need something like that
UserID (1)-->"Manager|Employee|Sales|"

Please help me how to write this query.

Regards

View 5 Replies View Related

Trying To Build CASE

Mar 22, 2004

I'm trying to add a CASE to my statement, I keep getting a syntax error. Can anyone see the issue? Should this CASE work?

Thanks for your thoughts,

Select tmp.Alternate_Name,dbo.tblClient.Salutation
CASE
WHEN (tmp.Alternate_Name > '') Then tmp.Alternate_Name As Card_Name
Else dbo.tblClient.Salutation AS Card_Name END
From dbo.tblClient INNER JOIN dbo.tblCards tmp ON dbo.tblClient.ClientID = tmp.ClientID

View 1 Replies View Related

Need Help To Build A Select

Sep 29, 2004

Hi there, I have 3 columns that contain the same kind of information and I would like to do a select that would return all the distinct records of all 3 colums. Any help woulb be appreciated.
Thanks

View 4 Replies View Related

Need Help To Build Querry

Jan 21, 2005

I have two tables linked with the colunm name systemId and I need to get all the systems responding to the condition (t1.software & 0000000001) = 1 and if they have any contacts I would like to see them.
Here is what I have for the moment however my querry do not return the system info if no contact exist and that is wrong.

select customers.customerId,customers.systemId,customers.country
from customers,contacts
where (customers.software & 0000000001) = 1
and customers.SystemId = contacts.SystemId
order by customerid

Systems
-SystemId
-CustomerId
-Name
...

Contacts
-ContactId
-SystemId
-Name
-Tel
...

View 1 Replies View Related

Please Help Me About Build New Table

Dec 12, 2005

please help me
i need for example
when my user clicke in the button a new table build in my sql database
please help me
 

View 1 Replies View Related

Final Build?

Nov 16, 1998

Anyone know the final build # for the RTM version?

Thanks

View 2 Replies View Related







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