Determing The Where Clause At Runtime

Nov 16, 2005

I am trying to set the WHERE clause in an SQL statement at runtime using a case statement like so

SELECT *

FROM table

WHERE   CASE @BrowseBy   
             
          WHEN 'Supplier' THEN
Supplier = @Value
           
            WHEN
'PriceRange' THEN Price > 1000
           
            WHEN
'BladeSpan' THEN BladeSpan = @Value
           
            WHEN
'MotorFinish' THEN FinishID = @Value
           
            WHEN
'BladeFinish' THEN BladeFinish1 = @Value or BladeFinish2 = @Value
                  END

the above code gives me a syntax error... does anyone know of another way to accomplish this?

Thanx

View 5 Replies


ADVERTISEMENT

SQL Server 2012 :: How To Modify ORDER BY Clause At Runtime Using Parameter

Jun 4, 2015

the code below works (this is only a quick dumbed down version of the actual code, it might not work 100% for all cases). Is it at all possible to exploit the functions that were added to SSQL since v. 2005 to simplify this code ?

In SSRS, a parameter allows the user to create a list of invoices (from CRM) to be ordered in any of the following ways the user prefers:

'Document Date (most recent date first)'
'Document Number (highest number first)'
'Document Date (most recent first) and Number'
'Document Number (lowest number first)'

The invoices have a (supposedly) sequential identity-generated number. However Accounting may want to set a different date than the creation date on some invoices. So there is no way the invoice numbers will be in the same sequence as the invoice dates.

So I just created the "sorting fields" - they appear as junk in the output dataset (just do not drop them in the SSRS tablix - they have to be part of the SELECT statement to be usable in the ORDER BY clause.

The code is:

DECLARE @ls_OrderBy varchar(80)
--'Document Number (highest number first)'
--'Customer and Document Date (most recent date first)'
--'Customer and Document Number (highest number first)'
--'Document Date (most recent first) and Number'

[code]....

View 9 Replies View Related

Determing Week Day Name

May 26, 2007

I want to determine name of week day using sql query. I used following:



Select datepart(weekday,mydate) from tablename;



This query returns day number but I want result as: Monday, Tuesday .....

View 1 Replies View Related

Determing The Identity Number After An INSERT INTO

Jan 5, 2006

All of my tables in my database have keys that are autonumbered (datatype int with identity set to 1).
Whenever I go to insert a new entry into the table I execute an INSERT INTO command and leave off the key field, so that it is automatically inserted with the new row.
However, I need to that number, so that I may insert it as foreign key into another table.  How would I go about retrieving this number?  I thought about doing a Max() on that field, but I am not confident that SQL server would always use a higher number than everything previous.  Is there a better way of accomplishing this?  Is my design flawed from the start?  Any feedback would helpful.  Thank you.

View 5 Replies View Related

Determing All Instances Defined On A Server

Mar 24, 2004

I'm in the process of writing some utility scripts which will
interface SQL2K to our backup storage system, Tivoli. In our shop we
"fire" the backup process from the Tivoli storage server by invoking a
command script on the client server. The issue I've run into is that
some of our servers were installed with Named Instances, either
instead of or in addition to the default instance.

Rather than hard coding these values in the scripts I'm looking for a
way to determine all the instance names on a server. The scripts
could then be generic without custom tailoring for current and future
servers (and instances).

Anyone have a solution?

Thanks,
Fred Prose - Arizona Supreme Court

View 2 Replies View Related

Determing SQL Server Patch Level

May 12, 2008

Sort of new to MSSQL and I have a problem with my maintenance script not deleting files on 2 out of 3 servers so I am trying to determine what patch level I am at.
'Server A' works as expected:

Microsoft SQL Server 2005 - 9.00.2050.00 (Intel X86)

Feb 13 2007 23:02:48

Copyright (c) 1988-2005 Microsoft Corporation

Standard Edition on Windows NT 5.2 (Build 3790: Service Pack 2)


These two servers don't:
Server B.

Microsoft SQL Server 2005 - 9.00.2050.00 (Intel X86)

Feb 13 2007 23:02:48

Copyright (c) 1988-2005 Microsoft Corporation

Standard Edition on Windows NT 5.2 (Build 3790: Service Pack 1)


Server C.
Microsoft SQL Server 2005 - 9.00.1399.06 (Intel X86)

Oct 14 2005 00:33:37

Copyright (c) 1988-2005 Microsoft Corporation

Standard Edition on Windows NT 5.2 (Build 3790: Service Pack 2)

So I can see where I should patch server B to SP2 but why does Server C report as 9.00.1399 SP2?

View 5 Replies View Related

How To Configure A Dataflow Task Having A Runtime Source Table Name And A Runtime Destination Table Name

Apr 18, 2008

Hi,

I am having a Data flow task in For each loop which will gets 100 sourcetable names and 100 target table names...

am having a simpleData flow task which trasferes from OLEDBSource to OLEDBDestination.
I am repeating the Dataflow task which transfers from sourcetablename extracted from for loop to a destination table var.

The problem am gettting is for the first table it is able to transfer correcly because I did mapping for those tables at design time...but for the next coming sourcetable-desttable (which r having different no of cols,datatypes) its giving Validation failed...and...needs to refresh metadata....

is there any way to refresh the metadata of Data flow task (I set the property of OLEDBSource validate external meta to false then also same error is coming)

Thanks
Radhika

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

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

SQL Runtime

Nov 30, 2007

Is there an SQL db that can function as a runtime stand alone app, inconjunction with a VB interface?

View 8 Replies View Related

Runtime DLL

Sep 18, 2007

Hello. I am trying to write a VB.net application to call our SSIS packages. I have seen several tutorials, including this one:

http://msdn2.microsoft.com/en-us/library/ms190901.aspx

Which calls for me to import:
Microsoft.SqlServer.Dts.Runtime
However, I don't have this DST Runtime DLL installed on my machine. I have installed "everything" in SQL Server Developer Edition and Visual Studio. Any idea how I can get this?

Thanks,
Chris

View 5 Replies View Related

Runtime Analysis

Jul 10, 2006

I just ran a testbed of 4 types of SQL queries:1. inline SQL with a StringBuilder2. managed sql3. SQL text processing (@SQL as varchar(5000); SET @SQL = 'SELECT ' + @var...)4. a regular sproc that has the columns and table name hard coded1,2, and 4 always end up at about the same time given the averages.3 is always at last 1.5 times slower, and usually closed to 2 times.1 and 2 both use StringBuilders, the code is a direct copy, and 3 is a copy as well.My managed SQL is:    [Microsoft.SqlServer.Server.SqlProcedure]    public static void usp_Items_Select_Managed(SqlString table, SqlString name,         SqlString value)    {        // sql          StringBuilder stringBuilder = new StringBuilder();        stringBuilder.AppendFormat(            "SELECT {0}.* FROM {0} WHERE {0}.{1} = {2}",            table,            col,            value            );        SqlConnection sqlConnection = new SqlConnection("context connection=true");        SqlCommand sqlCommand = new SqlCommand(stringBuilder.ToString(), sqlConnection);        sqlConnection.Open();        SqlContext.Pipe.Send(sqlCommand.ExecuteReader());        sqlConnection.Close();    }Is there anything wrong with my Managed SQL, or is this just the way that it is?Thanks

View 1 Replies View Related

DTS Runtime Error

May 2, 2001

I'm running a package on SQL Server 7, SP2 created in the same environment.
When running a package from DTS Designer, I get an execution status of "Error Occurred" in the Package Execution Status dialog on one of the data pump tasks I'm running along with the number of rows inserted. When I double-click on the task, I get the following message: " The Connection is currently being used by a task. The connection cannot be closed or reused".

Both the exception log for the task and the package, specified for error output, indicate the task ran successfully and the clients confirm that the appropriate number of rows have been inserted in the table. Has anyone encountered this error that can explain the cause/cure?

View 1 Replies View Related

Installshield And Sql Runtime

Jun 4, 2001

Hi,

When I'm using installshield to install sql runtime, I get the message "The Workstation service has not been started" during Configure SQL Server Agent. Does someone know what it means and how to solve it?


Thank you

View 1 Replies View Related

DTS Runtime Parameter

May 12, 2000

Hi Everyone,

I've an DTS package, which has an Execute SQL Task. I'm doing the operations based on a parameter. I need to pass that in runtime. Is there any way to do that in Execute SQL Task? BOL says that the runtime parameter can be set by giving a question mark(?). But when I tried this, it says, value not passed.


Thanks in advance.

View 1 Replies View Related

Database Runtime

Sep 4, 2007

I am Using Sql Server 2005 enterprise edition to develop an accounting system.
now i want to distribute this software to other cleints.
I have created a setup which includes all the components required for the run time of the software but i dont know how to include the sql server database in it.
as i know that i have created access based software i used to include the database file in the setup and it would work but in the case of sql server i dont know how to do it .
is there any runtime of sql server which needs to be downloaded or any other way out.

View 4 Replies View Related

Replace DB Name Runtime??

May 30, 2008

Hi.

I posted similar stuff in one of my previous topic. what i need to do is parse database name runtime
means sample example is

USE <%1>
GO
SELECT * FROM Table_Name


here instead of <%1> i need to pass Test DB name

USE Test
GO
SELECT * FROM Table_Name


my .sql file contains <%1> so i need to replace it

i tried like

declare @t varchar(50)
declare @chg22 varchar(500)

set @t = 'Test'
set @chg22 = 'USE <%1> GO'
set @chg22 = REPLACE(@chg22,'<%1>',@t)

exec(@chg22)
SELECT * FROM Table_Name

but i am not getting it..in above example i am just took one line select * from table_name but actually in .sql file more that 300 lines are there so i m not able to concatenate it..


T.I.A

View 4 Replies View Related

Overflow At Runtime

Nov 30, 2006

We run a regular query through Excel that is linked to a Microsoft SQL Server data source.

We have run this query routinely for the past few years. Suddenly this query has started returning an error message - “[Microsoft][ODBC SQL Server Driver] [SQL Server] Difference of two datetime columns caused overflow at runtime�. It seems to be a common error (as per Google search) however I don’t want to go messing around with something I don’t fully understand. Can anyone point me in the direction of what to look out for?

View 2 Replies View Related

Using The SQL Query At Runtime..

Mar 28, 2007

Hi,

Currently im using SQL queries in combination with ASP.NET..

I have currently only one table('Requests'), which has all the user info of name,id,studyrequested etc.. A person can request for any number of studies.

Now the prob is that from now on whenever a user requests for a new study not only should his details be stored in the Request table but also in a new Users table. In the Users table that particular users details must only be loaded once.. i.e. if the same user enrolls for another study his details should only be updated in the requests table and not in the Users table, since his details have already been loaded once in the Users Table..

While this works fine for new users, but what bout the old users already stored in the Requests table before the Users table existed.

Is there any way i could run a sql script only once at runtime, so that all the old legacy users are loaded once in to the Users Table.



Thanks,
Nitin

View 1 Replies View Related

INSER At Runtime?

Oct 2, 2006

Hi!Can anybody tell me what I'm missing here?I'm trying to insert a new record into a sql-database from code atruntime (not stored procedure),but get the following error message:"The 'strUn' is not permitted in this context.Only constants, expressions or variables allowed here.Column names are not permitted."//Create sql connectionSqlConnection con = new SqlConnection("server=LocalHost;database=Users;uid=geir;pwd=geir");//Open database connectioncon.Open();//Create variables to hold values from textboxesstring strUn = txtUsername.Text;string strPw = txtPassword.Text;//Create a sqlCommand to insert textbox values into sql-databaseSqlCommand sqlcmd = new SqlCommand();sqlcmd.CommandText = "INSERT INTO tblUsers(Username,Password)VALUES(strUn, strPw)";sqlcmd.Connection = con;try{sqlcmd.ExecuteNonQuery();}catch(SqlException ex){lblInfo.Text = "ExecuteNonQuery failed because: " +"" +ex.Message;}finally{con.Close();}

View 4 Replies View Related

SQL Server Runtime?

Feb 19, 2007

My boss claims that there is a free SQL server runtime. Is thistrue? I was only aware of MSDE. But I believe the connections arecapped at 5 in MSDE. If there is a free SQL server runtime, are thereany limitations to using it (performance, connection count)? Thanks.

View 2 Replies View Related

Can I Specify SubReport Name At Runtime?

Aug 4, 2006

I want to combine a bunch of reports (which are stand alone reports on there own) as subreports in a parent or master report. We have done this in Crystal Reprots in order to get a group of reports out in one file.

The issue with Reporting Services is the header and footers of the subreports are not rendered, so I have to repeat the logo information for each subreport in the body of the parent report. I can do this in a table or list or rectangle, but I have to do this for each subreport. Is there any way that I can specify the name of the subreport at runtime? That way I can put everything into a List and drive it from the database. I noticed that the dropdown to select the report name does not allow you to create an expression for this field.

View 3 Replies View Related

How Can I Get The Sql Statement Runtime?

Jan 25, 2008

is that have a function to get it?

View 3 Replies View Related

Runtime Parameters

Jan 19, 2006

Does anyone have an idea on how to handle runtime parameters for a package? Ideally I'd like to have the package prompt the user for a date range and then store the 2 dates in package variables for use later in the package.

View 1 Replies View Related

Set FontFamily Runtime

Mar 23, 2007

Hey Guyes,

I'm developing SSRS 2005 Reports in multi languages (i.e. regional language like hindi, marathi)

here i'm sending font name from database field with the help of expression in FontFamily Property of textbox as follows

FontFamily =IIF(Fields!DistrictNameRegional.Value<>Nothing,CStr(Fields!FontName.Value),"Tahoma")

It don't work.

But when i'm Writting like this

FontFamily =IIF(Fields!DistrictNameRegional.Value<>Nothing,"Shivaji01","Tahoma")

It works.

Plz tell me where I'm wrong with this.



View 4 Replies View Related







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