Select Minimum Between Two Values

Jul 27, 2006

Hello,
I need to select the minimum between the result of a function and a
number, but i can't find a smart way. By now I'm doing like the
following, but I think is very expensive because it evaluates the
function twice:

select case when (myfunction())<100 then (myfunction()) else 100 end

Any idea is appreciated.
Thank you
Regards


--
elimina carraro per rispondere via email

View 4 Replies


ADVERTISEMENT

Minimum/Maximum Of Two Values

Dec 6, 2004

Hallo Cracks,

what I try is a little bit heavy, maybe, but I only miss the minimum/maximum fuction - or I didn´t found it; not here in the Forum and also not in the onlinehelp of the SQL Server.

What I try to do:

I have 2 columns in my table; a start- and an end-date. For this period of time between end and start i have to calculate the days for the years. Here my thoughts (for the current year):

Is the startdate <= 31.12.2004 and the enddate >= 1.1.2004 i have to calculate die datediff between max(1.1.2004/startdate) and min(31.12.2004/enddate)

like this sqlstatement:

SELECT CASE WHEN dbo.Phases.phasenstart <= CAST(CAST(YEAR(GETDATE()) AS
varchar) + '-31-12' AS smalldatetime) AND dbo.Phases.phasenabschlussist >=
CAST(CAST(YEAR(GETDATE()) AS varchar) + '-01-01' AS smalldatetime)
THEN 365 ELSE 0 END AS Expr2,
FROM dbo.Phases
WHERE (phasenstart IS NOT NULL) AND (phasenabschlussist IS NOT NULL)

instead of 365 there must be the above calculation. Is start=3.1.2003 and end=30.1.2004 I expect as result only the 30 days in 2004.

thanks in advance and kind regards :-)
Cappu

View 2 Replies View Related

Display Minimum Of Two Values

Apr 13, 2015

I want the minimum of two values to be display like below without using the case

MIN(3.00,4.00)

output:

3.00

View 2 Replies View Related

Get Minimum And Maximum Values From Field?

Sep 16, 2012

I am trying to get the minimum and maximum values from a field in SQL Server 2008 Express, but I cannot even get started because I keep getting this error that I cannot figure out.

View 6 Replies View Related

Transact SQL :: Include Minimum Item Values Only

Aug 3, 2015

My sql gives me the results as shown in #TEMTAB Table.some times Mitem_id is repeated for the same Group_id,SGroup_id  with different item_id

ex: SQ322,SQ323,SQ324,SQ325 are repeated here.
CREATE TABLE #TEMTAB
(Group_id int, SGroup_id int, item_id int, Mitem_id varchar(10)
,YN varchar(2),value varchar(8),reason varchar(20))

[code]...

View 8 Replies View Related

T-SQL (SS2K8) :: Getting Minimum And Maximum Values In A Large Table

May 23, 2014

Table definition:

Create table code (
id identity(1,1)
code
parentcode
internalreference)

There are other columns but I have omitted them for clarity.

The clustered index is on the ID.

There are indexes on the code, parentcode and internalreference columns.

The problem is the table stores a parentcode with an internalreference and around 2000 codes which are children of the parentcode. I realise the table is very badly designed, but the company love orms!!

Example:
ID| Code| ParentCode| InternalReference|
1 | M111| NULL | 1|
2 | AAA | M111 | 2|
3 | .... | .... | ....|
4 | AAB | M111 | 2000|
5 | M222 | NULL | 2001|
6 | ZZZ | M222 | 2002|
7 | .... | .... | .... |
8 | ZZA | M222 | 4000|

The table currently holds around 300 millions rows.

The application does the following two queries to find the first internalreference of a code and the last internal refernce of a code:

--Find first internalrefernce
SELECT TOP 1 ID, InternalReference
FROM code
WHERE ParentCode = 'M222'
Order By InternalReference

-- Find last ineternalreference
SELECT TOP 1 ID, InternalReference
FROM code
WHERE ParentCode = 'M222'
Order By InternalReference DESC

These queries are running for a very long time, only because of the sort. If I run the query without the sort, then they return the results instantly, but obviously this doesn't find the first and last internalreference for a parentCode.

I realize the best way to fix this is to redesign the table, but I cannot do that at this time.

Is there a better way to do this so that two queries which individually run very slowly, can be combined into one that is more efficient?

View 7 Replies View Related

T-SQL (SS2K8) :: Select Minimum Date From Related Table

Apr 2, 2014

I am working on a query that seems very simple, but I just cannot seem to get it correct.

I want to be able to select Only 1 MemberAddress with the MIN(MoveDate) for each of the 3 Members. The results would be this:

Joe Smith, 2000-03-10, 1034 Sturgis Road, 115, Portland, Or, 77665
Sally Jones, 2001-01-02, 8970 Pierce Road, 25, Clear Bay, Washington, 96547
Beth Moore, 2006-05-30, 456 W. Blane Ave, NULL, Charleston, West Virgina, 56897

DECLARE @Members TABLE
(
MemberRowID INT IDENTITY(1,1) NOT NULL
,FirstName VARCHAR(20)
, LastName VARCHAR(20)

[Code]....

I am not opposed to using CTE, I really like them, but I cannot figure this one out. But I will try most anything.

View 4 Replies View Related

Select Values From One Table Based Upon Values In Another...

May 19, 2006

How do I:Select f1, f2, f3, from tb1 where f1=Select f1 from tb2 where f1='condition'?

View 3 Replies View Related

Transact SQL :: Return Set Of Values From SELECT As One Of Return Values From Stored Procedure

Aug 19, 2015

I have a stored procedure that selects the unique Name of an item from one table. 

SELECT DISTINCT ChainName from Chains

For each ChainName, there exists 0 or more StoreNames in the Stores. I want to return the result of this select as the second field in each row of the result set.

SELECT DISTINCT StoreName FROM Stores WHERE Stores.ChainName = ChainName

Each row of the result set returned by the stored procedure would contain:

ChainName, Array of StoreNames (or comma separated strings or whatever)

How can I code a stored procedure to do this?

View 17 Replies View Related

NULL Values In A SELECT In Another SELECT

Jan 23, 2008

Hi,I have a query like this :SELECTx1,x2,( SELECT ... FROM ... WHERE ...UNIONSELECT ... FROM ... WHERE ...) as x3FROM ...WHERE ...The problem is that I don't want to return the results where x3 isNULL.Writing :SELECTx1,x2,( SELECT ... FROM ... WHERE ...UNIONSELECT ... FROM ... WHERE ...) as x3FROM ...WHERE ... AND x3 IS NOT NULLdoesn't work.The only solution I found is to write :SELECT * FROM((SELECTx1,x2,( SELECT ... FROM ... WHERE ...UNIONSELECT ... FROM ... WHERE ...) as x3FROM ...WHERE ...) AS R1)WHERE R1.x3 IS NOT NULLIs there a better solution? Can I use an EXISTS clause somewhere totest if x3 is null without having to have a 3rd SELECT statement?There's probably a very simple solution to do this, but I didn't findit.Thanks

View 7 Replies View Related

How To Select From A List Of Values

Jun 21, 2006

Hi all. I need to create a select query in my program that will select from a list of values that are stored in a dataset. Let see this example:
selectcmd = "Select * from mytable where myfile =" ???????
cmd = New SqlCommand(selectCmd, da.SelectCommand.Connection)
 
The values I need to put on ????? are stored in a dataset. For example if the dataset is populated with the following values:
A
B
C
D
E
 
I would like to build a query like that:
selectcmd = "Select * from mytable where myfile = ‘A’ or ‘B’ or ‘C’ or ‘D’ or ‘E’ “
 
How can I do that?
Thanks.jsn
 

View 6 Replies View Related

Select 'many Values' From One Column

Jul 17, 2007

I'm building a textbox with search functionality towards SQL 2000.
The textbox is to include various search phrases, like "phrase1 phrase2 phrase3". Sort of like search engines where all words are considered. Do keep in mind that it's SQL2000 and not 2005. I've got all the strings I want to perform the search against in one column but various values in this column.
The only thing I've come up with is to create "WHERE columnName LIKE @phrase1 OR columnName LIKE @phrase2" where I inject % as apropiate and chop up the string, but I'm hoping this is not the solution because it doesn't seem really clean (with 10 search words) and today I'm not having a 'bad-hack' day so I want it better.
Whats is the best way of doing this?
Cheers!
 /Eskil

View 3 Replies View Related

Select Some Values From A Row And Insert On Another Row

Feb 12, 2008

I have a table wih multiple records and some has common values.
For example, new child row need to inherit some of parent's data.
Here is how I want to do:
Select [parent data1], [parent data2] from [TABEL] where id = parent
Insert INTO [TABLE]  ([child id], [child data1], [child data2] ) VALUES [child  id] [parent id] [parent id]...........
I was thinking about using Selected and Inserting events but not sure how.
Please help?
 Thanks,

View 1 Replies View Related

Query To ADD/SELECT Values From An SQL

Sep 16, 2004

Hello.

I need a query that will RETRIEVE a value from a database if it is present, but if the data isn't present, then the data will be INSERTed into the table.

Either way, I need the row returned at the end of the query.

I can do SELECT queries, but I don't have a clue as to how to proceed with branching statements.

For example:

User runs a query for "Canada".
Canada exists in the database, so the database returns Canada along with its ID.

Next user runs a query for "Chile".
Chile isn't in the database so a record is created and the ID (an IDENTITY field) is returned.

Does anyone know how I may accomplish this?

View 2 Replies View Related

Max Values In A Select Statement

May 22, 2002

I have a table which has 4 fields, patientid,testdate,testtype,results.
I want to select the most recent testdate by a patient regardless
of the results, or the testtype. I do however need those fields for my query.
I tried the below, but I get more than 1 record if the person has had two different types of tests. For instance if patient 100 has the following 2 records I just want the most recent

patientid testdate testype results

100 01/02/2002 TBI ASYMP
100 02/02/2001 PPD 00000

select max(testdate)as testdate,testtype, other_id_number
from vw_cms_tb_lasttest

What am missing?
Thanks
group by other_id_number,testtype
order by other_id_number,testtype

View 1 Replies View Related

Select Same Values From A Column.

May 22, 2007

bm

View 3 Replies View Related

BCP Help -Null Values In Select

Jan 26, 2004

I am using a bcp command to cretae a text file.

set @bcpcommand = 'bcp "select med + replicate('' '',10-datalength(med)),ml+ replicate('' '',20-datalength(ml)),iname + replicate('' '',10-datalength(iname)) from copy_tbl" queryout "'+ @filename + '" -U -P -c'

exec master..xp_cmdshell @bcpCommand

Some of the values in the select statement are Null values and are getting skipped in the text file .My output looks like
At A02 At1E
AtE A03 At2E
c100 c1230
I want them to allign but the third row has a null in the middle so it skips it and put the third value in the seconds place

View 2 Replies View Related

Getting Different Values From Select Statement

Jun 13, 2008

I am running a select statement against a function that is giving me different values depending on how it is called. When I run it through sql server management studio, I get the proper results, the default value column has the parameters default value. When I call it through my web app, I get this in the default value column:
*** ERROR OCCURRED level 2 (this is not a default value) ***

Why would the same sql statement get different results?

Here is the call:
select * from dbo.f_GetSProcParameters('webservices_BENEFICIAL_USES_DM_SELECT')

Here are the two functions:
---------------------------------------------------
USE [si_training_db]
GO
/****** Object: UserDefinedFunction [dbo].[f_GetSProcParameters] Script Date: 06/13/2008 09:29:21 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER function [dbo].[f_GetSProcParameters](@StoredProcedureName VARCHAR(128) )

Returns @sProcParameters Table(ParmName VarChar(128),
DefaultValue VarChar(128),
HasDefault Bit,
IsInput Bit)



/*
* DESCRIPTION : This function returns a table listing all the parameters of a stored
*procedure and the default values of those parameters.
*
* RETURNS : table
*
*
* ORIG AUTHOR : Josh Kinder
* DATE WRITTEN : 3/14/2006
*
* REVISIONS LOG
*
*ID/Date PC# Description
*------- --- ----------------------------------------------------------
*/


As

Begin

Declare
@Count SmallInt,
@Index SmallInt,
@CurParm VarChar(128),
@DefaultVal VarChar(128),
@IsInput BIT


/*----------------------------------------------------------------------------------------------------------------------------------*/
--EDIT CHECK -sProc only
/*----------------------------------------------------------------------------------------------------------------------------------*/

-- Check that the proc name is valid
If OBJECT_ID(@StoredProcedureName, 'P') Is Null
Begin
Goto ScriptErr
End

/*----------------------------------------------------------------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------------------------------------------------------------*/




Declare @ParmTable Table (Id SmallInt Identity Primary Key Clustered, ParmName VarChar(128))

Insert Into @ParmTable
Select
a.Name
From
SysColumns a
Inner Join SysObjects b On b.Id = a.Id
Where
b.Name = @StoredProcedureName

Select
@Count = Count(Id),
@Index = 1
From
@ParmTable


While (@Index<=@Count)
Begin

Select @CurParm = ParmName From @ParmTable Where Id = @Index

Set @DefaultVal = dbo.f_GetsProcParamDefaultValue(@StoredProcedureName,
@CurParm)

SELECT@IsInput = CASE WHEN params.is_output = 1 THEN 0 ELSE 1 END
FROMsys.procedures AS procs
INNER JOINsys.all_parameters AS params ON params.object_id = procs.object_id
LEFT JOINsys.types AS types ON types.system_type_id = params.system_type_id
AND types.user_type_id = params.user_type_id
WHEREprocs.is_ms_shipped = 0
AND params.name = @CurParm
AND procs.name = @StoredProcedureName

Insert Into @sProcParameters
(
ParmName,
DefaultValue,
HasDefault,
IsInput
)
Values
(
@CurParm,
@DefaultVal,
Case When @DefaultVal = 'NoDefaultExists' Then 0 Else 1 End,
@IsInput
)

Set @Index = @Index + 1
End

ScriptErr:
Return

End

---------------------------------------------------
USE [si_training_db]
GO
/****** Object: UserDefinedFunction [dbo].[f_GetsProcParamDefaultValue] Script Date: 06/13/2008 09:30:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER function [dbo].[f_GetsProcParamDefaultValue]
(
@StoredProcedureName VarChar(128),
@ParamName VarChar(128)
)

ReturnsVarChar(128)

/*
* DESCRIPTION : This function returns a table listing all the parameters of a stored
*procedure and the default values of those parameters.
*
The following copyright info is for the parsing algorithm to get the default value.
I obtained the code from SQL Farms Solutions and their only stipulation for use is
that the copyright info remain with the code. Although I customized it for us, it is
still their algorithm.

==================================================================================
Copyright © SQL Farms Solutions, www.sqlfarms.com. All rights reserved.
This code may be used at no charge as long as this copyright notice is not removed.
==================================================================================

* RETURNS : table
*
*
* ORIG AUTHOR : Josh Kinder
* DATE WRITTEN : 3/14/2006
*
* REVISIONS LOG
*
*ID/Date PC# Description
*------- --- ----------------------------------------------------------
*/

As

Begin

Declare
@minRow Int,
@maxRow Int,
@tmpInt Int,
@tmpText VarChar(4000),
@tmpCharPos1 Int,
@tmpCharPos2 Int,
@tmpCharPos3 Int,
@ParameterDefault VarChar(128),
@sProcTextVarChar(4000),
@DelimiterChar(1),
@Count SmallInt,
@Index SmallInt,
@CurTextVarChar(4000)

Select
@minRow = Null,
@maxRow = Null,
@Delimiter = char(13)

Declare @ProcText Table (Id Int Identity(1, 1) Primary Key Clustered,
ProcText VarChar(4000))

Insert Into @ProcText
Select
a.Text
From
SysComments a
Inner Join SysObjects b On b.Id = a.Id
Where
b.Name = @StoredProcedureName


Select
@Count = Count(Id),
@Index = 1
From
@ProcText


While (@Index<=@Count)
Begin

Select @CurText = Coalesce(@CurText,'') + ProcText From @ProcText Where Id = @Index

Set @Index = @Index + 1

End


/*----------------------------------------------------------------------------------------------------------------------------------*/
--EDIT CHECKS
/*----------------------------------------------------------------------------------------------------------------------------------*/

-- Check that the parameter name is valid for the proc
If Not Exists(
Select
1
From
INFORMATION_SCHEMA.PARAMETERS
Where
SPECIFIC_NAME = @StoredProcedureName
And PARAMETER_NAME = @ParamName
)
Begin
Set @ParameterDefault = '*** ERROR OCCURRED level 1 (this is not a default value) ***'
Goto ScriptErr
End

/*----------------------------------------------------------------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------------------------------------------------------------*/




/*----------------------------------------------------------------------------------------------------------------------------------*/
--Get sProc into a workable temporary table
/*----------------------------------------------------------------------------------------------------------------------------------*/

Declare @ProcContent Table (Idx Int Identity(1, 1) Primary Key Clustered,
ProcText VarChar(4000))

Insert Into @ProcContent
Select Value From dbo.f_Split(@CurText, @Delimiter, 1, 0)

-- Make sure that some rows were returned successfully
If @@ROWCOUNT = 0
Begin
Set @ParameterDefault = '*** ERROR OCCURRED level 2 (this is not a default value) ***'
Goto ScriptErr
End

/*----------------------------------------------------------------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------------------------------------------------------------*/





/*----------------------------------------------------------------------------------------------------------------------------------*/
--Get location of parm and get ready to parse
/*----------------------------------------------------------------------------------------------------------------------------------*/

-- Get the first line where the parameter is referenced in the proc code.
-- (the LIKE here is a little complex since it is possible that multiple parameters
-- will start with the same string. Most cases of interest are covered by the
-- conditions listed below).
Select
@minRow = Min(Idx)
From
@ProcContent
Where
ProcText Like '%' + @ParamName + ' %'
Or ProcText Like '%' + @ParamName + Char(9) + '%'
Or ProcText Like '%' + @ParamName + Char(10) + '%'
Or ProcText Like '%' + @ParamName + Char(13) + '%'
Or ProcText Like '%' + @ParamName + '=%'
Or ProcText Like '%' + @ParamName + '%=%'
Or ProcText Like '%' + @ParamName + ',%'

-- Check that the parameter is referenced in the code
If @minRow Is Null
Begin
Set @ParameterDefault = '*** ERROR OCCURRED level 3 (this is not a default value) ***'
Goto ScriptErr
End



-- Get the proc line where the word 'AS' is declared. 'AS' is required
-- upon proc creation to complete the variable declaration.
-- Note: This cover most cases of interest. There could be scenarios where
-- additional condition should be applied.
Select
@maxRow = Min(Idx)
From
@ProcContent
Where
ProcText Like '% AS'
Or ProcText Like '% AS '
Or ProcText Like '% AS' + Char(9)
Or ProcText Like '% AS' + Char(10)
Or ProcText Like '% AS' + Char(13)
Or ProcText Like 'AS %'
Or Upper(RTrim(LTrim(ProcText))) = Char(10) + 'AS'
Or Upper(RTrim(LTrim(ProcText))) = 'AS'
Or Upper(RTrim(LTrim(ProcText))) = 'AS' + Char(10)
Or Upper(RTrim(LTrim(ProcText))) = 'AS' + Char(13)
Or Upper(RTrim(LTrim(ProcText))) = 'AS' + Char(13) + Char(10)
Or Upper(RTrim(LTrim(ProcText))) = 'AS' + Char(10) + Char(13)

-- Check that the 'AS' string was found successfully
If @maxRow Is Null
Begin
Set @ParameterDefault = '*** ERROR OCCURRED level 4 (this is not a default value) ***'
Goto ScriptErr
End

/*----------------------------------------------------------------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------------------------------------------------------------*/






/*----------------------------------------------------------------------------------------------------------------------------------*/
--Parse and get the default value
/*----------------------------------------------------------------------------------------------------------------------------------*/

-- Get the first proc line of code where the parameter is referenced, for string processing,
-- and append to it all proc rows until the 'AS' string
Select
@tmpText = LTrim(RTrim(Replace(Replace(ProcText, Char(10), ''), Char(13), ''))) + ' '
From
@ProcContent
Where
Idx = @minRow




While @minRow < @maxRow
Begin
Set @minRow = @minRow + 1

Select
@tmpText = @tmpText + ' ' + LTrim(RTrim(Replace(Replace(ProcText, Char(10), ''), Char(13), ''))) + ' '
From
@ProcContent
Where
Idx = @minRow
End



-- Find the position of the parameter name. Delete all text before that position.
Set @tmpInt = Null
Set @tmpInt = PatIndex('%' + @ParamName + '%', @tmpText) - 1
Set @tmpText = Right(@tmpText, Len(@tmpText) - @tmpInt)



-- At this point we are nearly done:
-- We check whether the character '=' comes before the 'AS' or ',' string
-- If not- the parameter has no default value.
-- If so, we continue to find the value of the default parameter

Set @tmpCharPos1 = PatIndex('%=%', @tmpText)
Set @tmpCharPos2 = PatIndex('%,%', @tmpText)
Set @tmpCharPos3 = PatIndex('% AS %', @tmpText)



If @tmpCharPos1 <= 0
Or (@tmpCharPos1 > @tmpCharPos2 And @tmpCharPos2 > 0)
Or (@tmpCharPos1 > @tmpCharPos3 AND @tmpCharPos3 > 0)
Begin
-- The column does not have a default
Set @ParameterDefault = 'NoDefaultExists'
End
Else
Begin
-- Column has a default and it is left to find it.
-- First chop the string until the '=' character
Set @tmpInt = NULL
Set @tmpInt = PatIndex('%=%', @tmpText) - 1
Set @tmpText = LTrim(Right(@tmpText, Len(@tmpText) - @tmpInt))

-- Now, we p*** the remaining string until we get a ',' or a ' ' character
Set @tmpCharPos1 = NULL
Set @tmpCharPos2 = NULL

Set @tmpCharPos1 = PatIndex('%,%', @tmpText)
Set @tmpCharPos2 = PatIndex('% %', @tmpText)

Set @tmpInt = NULL


If @tmpCharPos2 > @tmpCharPos1 AND @tmpCharPos1 > 0
Set @tmpInt = @tmpCharPos1 - 1
Else
Set @tmpInt = @tmpCharPos2 - 1


If @tmpInt <= 0
Begin
Set @ParameterDefault = '*** ERROR OCCURRED level 5 (this is not a default value) ***'
Goto ScriptErr
End


Set @ParameterDefault = SubString(@tmpText, 1, @tmpInt)



-- If the parameter default is a string, then we will have an '' at each side of it.
-- These last lines of code will get rid of the ''.
If Len(@ParameterDefault) >= 1
If Right(@ParameterDefault, 1) = ''''
Set @ParameterDefault = Left(@ParameterDefault, Len(@ParameterDefault) - 1)

If Len(@ParameterDefault) >= 1
If Left(@ParameterDefault, 1) = ''''
Set @ParameterDefault = Right(@ParameterDefault, Len(@ParameterDefault) - 1)
End

/*----------------------------------------------------------------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------------------------------------------------------------*/






Goto ScriptExit

ScriptErr:

ScriptExit:

Return @ParameterDefault

End

View 1 Replies View Related

Select Distinct Values

Jun 25, 2014

I have a problem when selecting distinct values from a table. I want to select those distinct numbers with a code that I want. To make it more clear i`ll show it on an example.I have the following table:

tel_no | code | id_res
+-----------+--------------+-----------
0742062141 | a-not answer | 1
0742062141 | a-not answer | 2
0742062141 | c-answer | 3
0754231456 | a-not answer | 4
0754231456 | a-not answer | 5

When I use the following query it returns the distinct number but with the first code it finds:

select a.* from test_funnel as a
inner join
( select distinct tel_no,MIN(id_res) as id_res
from test_funnel

[code]....

View 3 Replies View Related

Select Does Not Return Values

Sep 15, 2006

I am new to SQL and I am trouble-shooting a problem with a home-grown app someone else wrote using PERL. It has a web interface with names of boards. I found the program where i need to add the board names into and did that. The new board names show up in the drop-down list in the Web page for the app. Alerts are sent to the new board names and show up on the new boards. Users are granted access to the new boards and they can clear items off the new boards. Yet when i try to use a report function for the new boards i added, nothing is returned. I even ran a simple SQl select statement specifying the new board names and nothing is returned. The older board names, some of which i added myself, return values. I don't know what is going on. Any help is appreciated.

View 3 Replies View Related

How To Select Not Null Values

Oct 4, 2006

hi, i have 5 columns in my table

name age phone sex salary

dani 21 1233 m

see this output, there salary is null.
actually i want to use * (ie)
select * from emp, if i use this the following output has to come

name age phone sex

dani 21 1233 m

becos there is no value in salary column.
so please tall me how to do this,please give me query to do this.

View 5 Replies View Related

Select Row Values To Be Column Name

Jul 20, 2005

I am new to sql query and have a question.I would like to display row column values as column names.questions table consisted ofquestion_id, group_id, questionresponse table consisted ofresponse_id, group_id, question_id, answerI would like to display the answer responses under the columns ofquestions : such asresponse_id, question(1), question(2), question(3)...It will be greatly appreciated if someone help me to get this down.Jason

View 2 Replies View Related

Get The Minimum Value

Sep 17, 2007

In my table I have values like (2,3). I want to get the minimum value from the column

View 12 Replies View Related

Use Listbox Values To Do Select Statement

May 20, 2007

Hi,
I have SQL database 2000 which has one table Sheet1, I retrieved the columns in the ListBox, then chosed some of them and moved it to ListBox2.
The past scenario worked great, and I checked the moved values, it was succesfully moved, but when I tried to copy the values in ArrayList to do a select statement it didn't worked at all.
public string str;protected void Button3_Click(object sender, EventArgs e)
{ArrayList itemsSelected = new ArrayList(); string sep = ",";
//string str;for (int i = 0; i < ListBox2.Items.Count; i++)
{if (ListBox2.Items[i].Selected)
{
itemsSelected.Add(ListBox2.Items[i].Value);
}
int itemsSelCount = itemsSelected.Count; // integer variable which holds the count of the selected items.
str = ListBox2.Items[i].Value + sep;
Response.Write(str);
}
 SqlConnection SqlCon = new SqlConnection("Data Source=AJ-166DCCD87;Initial Catalog=stat_rpt;Integrated Security=True;Pooling=False");
String SQL1 = "SELECT " + str + " from Sheet1"; SqlDataAdapter Adptr = new SqlDataAdapter(SQL1, SqlCon);
SqlCommandBuilder CB = new SqlCommandBuilder(Adptr);DataTable Dt = new DataTable();
Adptr.Fill(Dt);
//return Dt;
GridView1.DataBind();
SqlCon.Close();
}
I did some changes and the new error message is
Incorrect syntax near the keyword 'from'.
Thank you

View 6 Replies View Related

Select All Table Values By Default

May 20, 2007

Hi, I have something similar to the following:  CREATE PROCEDURE dbo.MySproc    @columnVal int = nullASBEGIN       SELECT        *     FROM        MyTable    WHERE        MyTable.column = @columnVal    END  If columnVal is not passed into the stored proc i want it to just select everything from 'MyTable' (without the WHERE clause)....how can I do this in as few lines of code possible?thanks 

View 3 Replies View Related

Select Statement When Values Are Not Null

Sep 4, 2007

Hi.
I have an sql table which contains a number and a name. I would like to create a select statement that will display these two fields in the format :
"number | name", but if there is a null value in the number it will display only the name and vice versa.
How can I do it ?
Any help is appreciated.

View 1 Replies View Related

Updating Values During SELECT Using CTE And Row_Number()

Sep 19, 2007

Hi,
I'm very new to stored procedures and I've been searching on google to find a way to custom page my results using SQL Server 2005. I'm trying to use Row_Number() and a CTE to keep things efficient and scaleable but I keep getting an error next to my UPDATE statement.
I get the following error: "[Microsoft][ODBC SQL Server Driver][SQL Server]Incorrect syntax near the keyword 'UPDATE'."
The sproc works without the UPDATE statement. Does anyone know where I need to put the UPDATE statement to update the "searched" field for each record selected?
 
CREATE PROCEDURE [zk_update_request_england](@property_type     tinyint,@market_status     tinyint,@price             int,@bedrooms          tinyint,@search_location   varchar(30),@search_district   varchar(30),@PageSize   int,@PageIndex  int)
AS
BEGIN
WITH SearchResults AS(
   UPDATE dbo.zk_request_england   SET    searched = searched + 1   WHERE  property_type = @property_type   AND    market_status = @market_status   AND    bedrooms = @bedrooms   AND    search_location = @search_location   AND    search_district = @search_district   AND    min_price <= @price   AND    max_price >= @price 
   SELECT user_id,          min_price,          max_price,          property_description,          searched,          ROW_NUMBER() OVER (ORDER BY max_price DESC) AS RowNumber   FROM   dbo.zk_request_england   WHERE  property_type = @property_type   AND    market_status = @market_status   AND    bedrooms = @bedrooms   AND    search_location = @search_location   AND    search_district = @search_district   AND    min_price <= @price   AND    max_price >= @price
)
   SELECT user_id,          min_price,          max_price,          property_description   FROM   SearchResults    WHERE RowNumber BETWEEN (@PageIndex - 1) * @PageSize + 1 and @PageIndex*@PageSize
END
 
Thanks in advance for any help.

View 3 Replies View Related

Connecting To A Database And Select Values

Jun 3, 2008

Hello there i try to retrieve some data from my table but i cannot get it to get me the ItemID from the table
here is the connection string it jumps right at the start of the loop strconnection = New SqlConnection("Data source = REPORT-SRVR; Initial Catalog=Cincinnati_Tan_Company;Persist Security Info=True;User ID=basic_user;Password=ctc_user;")
Dim cmdstring As String = "select ItemID, Price FROM Office_Items WHERE Description ='" & item(INTINDEX) & "'" '
strconnection.Open()CMD = New SqlCommand(cmdstring, strconnection)
mYReader = CMD.ExecuteReader()
If mYReader.Read = True ThenWhile mYReader.Read
ItemID = mYReader.Item("ItemID")Session("ItemID") = mYReader.Item("ItemID")
Session.Add("ItemID", ItemID)price = mYReader.Item("price")
Session("price") = mYReader.Item("price")Session.Add("price", price)
End While
End If
mYReader.Close()

View 3 Replies View Related

SELECT Question, Grouping Values

Jan 22, 2006

What is the best way to build a SQL query to extract data from a table in this manner:

COLA COLB COLC DATE
01 01 01 04/15/1988
01 01 01 11/23/1997
01 01 01 02/02/2005
01 02 01 6/14/1990
01 02 01 10/30/1999
01 02 02 4/24/2001

How would I select Row 3, 5, and 6 above (In other words, from each set where COL A B & C are equivalent, grab the most recent date?)

Thanks!!!

View 1 Replies View Related

SELECT Statement From A List Of Values?

Jul 12, 2012

I would like to write a select statement where I specify a list of values in the 'Select' line, and would like the output to have one line for each element.

I tried using Case with no success.

For example:

Select a.id, a.timestamp, ('rowA','rowB') as 'Tag' from tableOne a where a.id = '1'

So the 'where' line would produce one row, however, the overall statement would produce two.

ID TimeStamp Tag
--------------------------------
1 2012-12-12 rowA
1 2012-12-12 rowB

View 4 Replies View Related

Insert Proc With Both Select And Values

May 18, 2004

I'm trying to write a Stored Proc to Insert records into a table in SQL Server 2000. The fields in the records to be inserted are from another table and from Parameters. I can't seem to figure out the syntax for this.

I created a test in MS Access and it loooks like this:

INSERT INTO PatientTripRegionCountry_Temp ( CountryID, RegionID, Country, PatientTripID )
SELECT Country.CountryID, Country.RegionID, Country.Country, 2 AS PatientTripID
FROM Country

This works great in Access but not in SQL Server. In SQL Server 2 = @PatientTripID

ANY SUGGESTIONS ON HOW TO HANDLE THIS?

View 7 Replies View Related

T-SQL (SS2K8) :: Select One Of Three Values That Are Not NULL?

May 6, 2014

I am working on some data that is JOINing to another table. Not a big thing. In the child table, there are different values for a single ID. I want to be able to select the Max ColorID that is Not Null, for each distinct CarID. The CarID is what I am joining the other table with. I need selecting the distinct row with the Max ColorID that is not Null. All this data is made up, so nothing looks logical in the design.

DECLARE @ColorList TABLE
(
CarID float
, ColorID int
)
INSERT INTO @ColorList
SELECT 1.55948815793043E+15, 9 UNION ALL
SELECT 1.55948815793043E+15, 27 UNION ALL

[code]....

So this would be the resultset:

1.55948815793043E+15, 27
1.62851796905743E+15, 27
1.51964586107807E+15, 9
1.55948815793043E+15, 27
1.47514023011517E+15, 5
1.64967408641916E+15, 27
1.51964586107807E+15, 9
1.56103326128036E+15, 27
1.49856249351719E+15, 9
1.5736407022847E+15, 6
1.64664602022073E+15, 27
1.51964244007807E+15, 27

View 3 Replies View Related

T-SQL (SS2K8) :: How To Select Columns That Have Some Values Only

Jun 1, 2015

I have event table that containing multiple events, and many of them are empty. I'd like to select only the columns that have values in them.

Here is an example:

IF OBJECT_ID('tempdb..#events') IS NOT NULL
DROP TABLE #events
create table #events (eventId int,
Category varchar(250),
events1 varchar(250),

[Code] .....

In this case, I'd like to run a query like this one(skip Column Event3):

Select eventId,Category,events1,events2,events4,events5 From #events

View 4 Replies View Related







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