Concatenating Column Values In SELECT Statement
Aug 31, 2000
I'm puzzled as to how to express what I want in a stored procedure. Assume two columns, Surname and GivenName. The surname might be missing. When I originally wrote this app in Access, I used the following expression:
SELECT Iif( IsNull(Surname), GivenName, Surname + ", " + GivenName ) AS Agent
FROM Agents;
I've looked at the syntax for CASE but I can't figure out exactly how to say what I intend, particularly the AS Agent column aliasing.
Any help greatly appreciated. Please cc me privately so I receive your assistance at once!
TIA,
Arthur
View 1 Replies
ADVERTISEMENT
Aug 22, 2007
I have an SQL Select statement that I need to add a column to called SalePrice, the SalePrice column needs to be calculated by adding together the values of 12 columns, then multiplying that value by the value in a another column to calculate margin. My issue is that I can only get it to add 7 column values together, if I add any more columns to the equation it just returns and null result. My DB is SQL 2005 Express SP2. My select statement is below: SELECT dbo.MFG_DATA_Machines.ID, dbo.MFG_DATA_Machines.MachineName, dbo.MFG_DATA_Parts_CPU.PartDescription AS CPU,
dbo.MFG_DATA_Parts_CPU.PartCost AS CPUCost, dbo.MFG_DATA_Parts_Motherboard.PartDescription AS Motherboard,
dbo.MFG_DATA_Parts_Motherboard.PartCost AS MotherboardCost, dbo.MFG_DATA_Parts_RAM.PartDescription AS RAM,
dbo.MFG_DATA_Parts_RAM.PartCost AS RAMCost, dbo.MFG_DATA_Parts_HDD.PartDescription AS HDD,
dbo.MFG_DATA_Parts_HDD.PartCost AS HDDCost, dbo.MFG_DATA_Parts_OpticalDrive.PartDescription AS OpticalDrive,
dbo.MFG_DATA_Parts_OpticalDrive.PartCost AS OpticalDriveCost, dbo.MFG_DATA_Parts_Video.PartDescription AS Video,
dbo.MFG_DATA_Parts_Video.PartCost AS VideoCost, dbo.MFG_DATA_Parts_OS.PartDescription AS OS, dbo.MFG_DATA_Parts_OS.PartCost AS OSCost,
dbo.MFG_DATA_Parts_Modem.PartDescription AS Modem, dbo.MFG_DATA_Parts_Modem.PartCost AS ModemCost,
dbo.MFG_DATA_Parts_FloppyDrive.PartDescription AS FloppyDrive, dbo.MFG_DATA_Parts_FloppyDrive.PartCost AS FloppyDriveCost,
dbo.MFG_DATA_Parts_CardReader.PartDescription AS CardReader, dbo.MFG_DATA_Parts_CardReader.PartCost AS CardReaderCost,
dbo.MFG_DATA_Parts_PowerSupply.PartDescription AS PowerSupply, dbo.MFG_DATA_Parts_PowerSupply.PartCost AS PowerSupplyCost,
dbo.MFG_DATA_Parts_CaseType.PartDescription AS CaseType, dbo.MFG_DATA_Parts_CaseType.PartCost AS CaseTypeCost,
dbo.MFG_DATA_Machines.Notes, dbo.MFG_DATA_Machines.MarginPercent, dbo.MFG_DATA_Machines.PriceOverride,
(dbo.MFG_DATA_Parts_CPU.PartCost + dbo.MFG_DATA_Parts_Motherboard.PartCost + dbo.MFG_DATA_Parts_RAM.PartCost + dbo.MFG_DATA_Parts_HDD.PartCost
+ dbo.MFG_DATA_Parts_OpticalDrive.PartCost + dbo.MFG_DATA_Parts_Video.PartCost + dbo.MFG_DATA_Parts_OS.PartCost + dbo.MFG_DATA_Parts_Modem.PartCost
+ dbo.MFG_DATA_Parts_FloppyDrive.PartCost + dbo.MFG_DATA_Parts_CardReader.PartCost + dbo.MFG_DATA_Parts_PowerSupply.PartCost + dbo.MFG_DATA_Parts_CaseType.PartCost)
* ((dbo.MFG_DATA_Machines.MarginPercent + 100) / 100) AS SalePrice
FROM dbo.MFG_DATA_Machines LEFT OUTER JOIN
dbo.MFG_DATA_Parts_CaseType ON dbo.MFG_DATA_Machines.CaseType = dbo.MFG_DATA_Parts_CaseType.ID LEFT OUTER JOIN
dbo.MFG_DATA_Parts_Motherboard ON dbo.MFG_DATA_Machines.Motherboard = dbo.MFG_DATA_Parts_Motherboard.ID LEFT OUTER JOIN
dbo.MFG_DATA_Parts_Video ON dbo.MFG_DATA_Machines.Video = dbo.MFG_DATA_Parts_Video.ID LEFT OUTER JOIN
dbo.MFG_DATA_Parts_RAM ON dbo.MFG_DATA_Machines.RAM = dbo.MFG_DATA_Parts_RAM.ID LEFT OUTER JOIN
dbo.MFG_DATA_Parts_PowerSupply ON dbo.MFG_DATA_Machines.PowerSupply = dbo.MFG_DATA_Parts_PowerSupply.ID LEFT OUTER JOIN
dbo.MFG_DATA_Parts_OS ON dbo.MFG_DATA_Machines.OS = dbo.MFG_DATA_Parts_OS.ID LEFT OUTER JOIN
dbo.MFG_DATA_Parts_OpticalDrive ON dbo.MFG_DATA_Machines.OpticalDrive = dbo.MFG_DATA_Parts_OpticalDrive.ID LEFT OUTER JOIN
dbo.MFG_DATA_Parts_Modem ON dbo.MFG_DATA_Machines.Modem = dbo.MFG_DATA_Parts_Modem.ID LEFT OUTER JOIN
dbo.MFG_DATA_Parts_HDD ON dbo.MFG_DATA_Machines.HardDisk = dbo.MFG_DATA_Parts_HDD.ID LEFT OUTER JOIN
dbo.MFG_DATA_Parts_FloppyDrive ON dbo.MFG_DATA_Machines.FloppyDrive = dbo.MFG_DATA_Parts_FloppyDrive.ID LEFT OUTER JOIN
dbo.MFG_DATA_Parts_CPU ON dbo.MFG_DATA_Machines.CPU = dbo.MFG_DATA_Parts_CPU.ID LEFT OUTER JOIN
dbo.MFG_DATA_Parts_CardReader ON dbo.MFG_DATA_Machines.CardReader = dbo.MFG_DATA_Parts_CardReader.ID
View 2 Replies
View Related
Apr 5, 2006
I have a customer who has recently migrated their SQL server to a newserver. In doing so, a portion of a stored procedure has stoppedworking. The code snippet is below:declare @Prefixes varchar(8000),declare @StationID int-- ...select @Prefixes = ''select @Prefixes = @Prefixes + Prefix + '|||'from Devicewhere Station_ID = @StationIDEssentially, we are trying to triple-pipe delimit all the deviceprefixes located at a specified station. This code has workedflawlessly for the last 10 months, but when the database was restoredon the new server, @Prefixes only contains the prefix for the lastdevice.Is there a server, database, or connection option that permits this towork that I am not aware of? Why would this work on the old server andnot on the new? (BTW - both servers are running SQL 2000 StandardSP4).Thanks!
View 6 Replies
View Related
Aug 1, 2007
Hello,
I have such a problem. Need to add additional column to my query. The column should consist of set of fixed number (same as number of query rows) values (text). At start thought it's simple but now Im lost. Is there any chance to do it. Apreciate any help. I need to tell that I have only access to select on this database so no use of operation on tables.
View 6 Replies
View Related
Nov 26, 2015
I am writing a query and have the bulk of it already written.
I am looking at a table that contains customer orders. There is a column named Customer_Order.Status Available values for this column is R, F, H, and C.
I'd like for my query to return all lines that have the value R, F, H.
My where clause is written like this
WHERE CUSTOMER_ORDER.SITE_ID = 'XXX' AND CUSTOMER_ORDER.STATUS = ('R','H','F')
I know I'm missing something....
View 3 Replies
View Related
Jan 9, 2015
Ok I have a query "SELECT ColumnNames FROM tbl1" let's say the values returned are "age,sex,race".
Now I want to be able to create an "update" statement like "UPATE tbl2 SET Col2 = age + sex + race" dynamically and execute this UPDATE statement. So, if the next select statement returns "age, sex, race, gender" then the script should create "UPDATE tbl2 SET Col2 = age + sex + race + gender" and execute it.
View 4 Replies
View Related
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
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
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
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
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
Apr 16, 2008
Hi Guys,
I am converting Access queries to SQL. One query has a string of IIF statements that can concatenate several strings into one field. For instance:
IIf([Hot Dogs]=-1,"* Wants a Hot Dog ","") &
IIf([Hamburger]=-1,"*Wants a Hamburger ","") &
IIf([mustard]=-1,"*add mustard ","") &
IIf([fries]=-1,"*Include Fries ","") &
IIf([Chips]=-1,"*Include Chips ","")
Consequently the output could be:
*Hamburger *add mustard *Include Chips
I know I can use the ‘Case When Then’ statement but how do I concatenate?
Thanx
View 4 Replies
View Related
Jul 11, 2006
Hey everyone,
This is probably a very simple question, but I am just stumped. I am storing different name parts in different fields, but I need to create a view that will pull all of those fields together for reports, dropdowns, etc.
Here is my current SELECT statement:
SELECT m.FName + SPACE(1) + m.MName + SPACE(1) + m.LName + ', ' + m.Credentials AS Name,
m.JobTitle,
m.Company,
m.Department,
m.Address,
m.City + ', ' + m.State + ' ' + m.Zipcode AS CSZ,
m.WorkPhone,
m.FAX,
m.Email,
c.Chapter,
m.Active,
s.Sector,
i.Industry
FROM tblMembers m
LEFT OUTER JOIN tblChapters c
ON m.ChapterID = c.ChapterID
LEFT OUTER JOIN tblSectors s
ON m.SectorID = s.SectorID
LEFT OUTER JOIN tblIndustries i
ON m.IndustryID = i.IndustryID
WHERE m.DRGInclude = 1
My problem is that I don't know how to test for NULL values in a field. When you concatenate fields that contain NULL values, the entire contactenated field returns NULL. I am not aware of an IF statement that is available within the SELECT statement.
The first thing I would like to accomplish is to test to see if MName contains NULL. If it does I do not want to include + SPACE(1) + m.MName in the clause. Then, if Credentials contains NULL I do not want to include + ', ' + m.Credentials in the clause.
Can someone tell me what I am missing? Is there a function that I can use for this?
Thanks,
View 8 Replies
View Related
Jul 20, 2005
Hello All,Is there a way to run sql select statements with column numbers inplace of column names in SQLServer.Current SQL ==> select AddressId,Name,City from AddressIs this possible ==> select 1,2,5 from AddressThanks in Advance,-Sandeep
View 1 Replies
View Related
Sep 21, 2007
Hello all,
I have been working with a DetailsView control for the past week and it is a great control, but also lacks on some departments. Anyhow I need to know what the best approach for this scenerio would be?
I have a SqlDataSource"
<asp:SqlDataSource ID="SqlUpsertAffiliateDetails" runat="server" ConnectionString="<%$ ConnectionStrings:connectionstring %>"
SelectCommand="SELECT am.affiliate_id AS AffiliateId, am.member_id AS MemberId, m.First_Name, m.Last_Name, am.category_id AS CategoryId, ac.category_name, am.profile_web_address AS WebAddress, am.profile_email_1 AS Email, am.comments AS Comments, am.date_modified FROM tAffiliateMaster AS am WITH (NOLOCK) INNER JOIN tAffiliateCategories AS ac WITH (NOLOCK) ON am.category_id = ac.category_id INNER JOIN rapdata..Member AS m WITH (NOLOCK) ON am.member_id = m.Member_Number WHERE (am.affiliate_id = @AffiliateId)"
UpdateCommand="spUpsertAffiliateProfile" UpdateCommandType="StoredProcedure">
<SelectParameters>
<asp:QueryStringParameter Name="AffiliateId" QueryStringField="affiliate_id" />
</SelectParameters>
<UpdateParameters>
<asp:Parameter Name="Action" Type="Byte" DefaultValue="2" />
</UpdateParameters>
</asp:SqlDataSource>
And my SP:/* 09-19-07 Used to update affiliate profile */
CREATE PROCEDURE spUpsertAffiliateProfile
@Action tinyint,
@AffiliateId int,
@MemberId int = -1,
@CategoryId int,
@WebAddress varchar(50),
@Email varchar(50),
@Comments varchar(1500)
AS
SET NOCOUNT ON
-- Find errors first, check is not needed if deleting
IF @Action <> 3
IF NOT EXISTS (SELECT Member_Number FROM rapdata..Member_Association WHERE Member_Number = @MemberId AND Status = 'A' AND Association_ID = 'TRI' AND Bill_Type_Code LIKE '%AF%')
BEGIN
SELECT retval = 'A qualified member ID was NOT found. Action Failed.', errorcount = 1, 0 AS affiliate_id
RETURN
END
IF @Action = 1
IF EXISTS (SELECT member_id FROM tAffiliateMaster WHERE member_id = @MemberId)
BEGIN
SELECT retval = 'This member has already been listed. Action Failed.', errorcount = 1, 0 AS affiliate_id
RETURN
END
IF @Action = 1 AND @AffiliateId = 0-- insert
BEGIN
INSERT INTO tAffiliateMaster
(member_id, category_id, profile_web_address, profile_email_1, comments)
VALUES
(@MemberId, @CategoryId, @WebAddress, @Email, @Comments)
SELECT retval = 'Record Entered', errorcount = 0, @@IDENTITY AS affiliate_id
RETURN
END
ELSE IF @Action = 2 AND @AffiliateId > 0-- update
BEGIN
UPDATE
tAffiliateMaster
SET
category_id= @CategoryId,
profile_web_address=@WebAddress,
profile_email_1=@Email,
comments=@Comments
WHERE
affiliate_id = @AffiliateId AND member_id = @MemberId
SELECT retval = 'Record Updated', errorcount = 0, @AffiliateId AS affiliate_id
RETURN
END
ELSE IF @Action = 3 AND @AffiliateId > 0-- delete
BEGIN
DELETE
tAffiliateMaster
WHERE
affiliate_id = @AffiliateId
SELECT retval = 'Record Deleted', errorcount = 0, 0 AS affiliate_id
RETURN
END
GO
My question is how will I be able to return the retval? Will I need to do it within the code behind of the SqlDataSource Updated Event?
Thanks!
View 3 Replies
View Related
Feb 9, 2006
hi,
my sample SQL Server DB Tables are like,
SID Skill
--- -------
1 JAVA
2 ORACLE
3 C
4 C++
PID Skillset
--- ---------
1 1,2,3
2 2,4
3 1,2,3,4
4 3
I need the Query to display Person skills as follows...
PID Skillset
--- --------------
1 Java,Oracle,C
2 Oracle,C++
3 Java,Oracle,C,C++
4 C
and another query for Search..
if i give the search string as Java,C or i will pass the SID 1,3. i need to diplay the person records which contains the SID.
output will be...
PID Skillset
--- --------------
1 Java,Oracle,C
3 Java,Oracle,C,C++
4 C
or
PID Skillset
--- ---------
1 1,2,3
3 1,2,3,4
4 3
Plz help meee..
Thanking you in advance for your help.
View 1 Replies
View Related
Jan 12, 2005
Hello,
This may be a strange request, but I am going to ask about it anyways.
Say for example if I have a table named TEST and in the table there is a column named NUMBERS, such that it is like this:
NUMBERS
1
2
3
4
How could I use a select statement in a way that a comma would seperate every return value, such that if I go 'Select NUMBERS from TEST' I would get:
1,2,3,4
Instead of:
1
2
3
4
Any ideas?
Thanks
View 1 Replies
View Related
May 8, 2008
Hi,
I have a table called emp, having 2 field name & sex
values are:
name sex
a 1
b 2
c 1
now i want to display the values in above table as like below...
name sex
a Male
b Female
c Male
How to do that...?
View 11 Replies
View Related
Jan 10, 2008
Hi,
I got a really simple question here. Say I have a table with
ID, Name
1, A1
2, A2
3, A3
....
10, A10
Now I want to combine the names into another table grouped by their ID (say 1-5, 6-10), so this new table has two names instead of 10:
A1 A2 A3 A4 A5
A6 A7 A8 A9 A10
Is there a function that allows me to 'combine' the names from a select statement?
Thanks in advance,
Steven
View 6 Replies
View Related
Sep 17, 2007
Hi all
I have the following tables:
Code Snippet
CREATE TABLE #Lkp_Circle
(
ID INT ,
Abbreviation varchar(50)
)
GO
CREATE TABLE #Lkp_OtherCircles
(
Circle varchar(50)
)
GO
CREATE TABLE #Tbl_User
(
ID INT,
Name VARCHAR(50),
IsActive bit
)
GO
CREATE TABLE #Tbl_UserDetails
(
AssociateID INT,
CircleID INT
)
GO
INSERT INTO #Lkp_Circle VALUES (1,'C1')
INSERT INTO #Lkp_Circle VALUES (2,'C2')
INSERT INTO #Lkp_Circle VALUES (3,'C3')
INSERT INTO #Lkp_Circle VALUES (4,'C4')
INSERT INTO #Lkp_Circle VALUES (5,'C5')
INSERT INTO #Lkp_Circle VALUES (6,'C6')
INSERT INTO #Lkp_Circle VALUES (7,'C7')
GO
INSERT INTO #Lkp_OtherCircles VALUES ('C3')
INSERT INTO #Lkp_OtherCircles VALUES ('C4')
INSERT INTO #Lkp_OtherCircles VALUES ('C5')
INSERT INTO #Lkp_OtherCircles VALUES ('C6')
GO
INSERT INTO #Tbl_User VALUES ( 101,'U 1','True')
INSERT INTO #Tbl_User VALUES ( 102,'U 2','True')
INSERT INTO #Tbl_User VALUES ( 103,'U 3','True')
INSERT INTO #Tbl_User VALUES ( 104,'U 4','True')
INSERT INTO #Tbl_User VALUES ( 105,'U 5','True')
GO
INSERT INTO #Tbl_UserDetails VALUES(101,3)
INSERT INTO #Tbl_UserDetails VALUES(102,4)
INSERT INTO #Tbl_UserDetails VALUES(103,5)
INSERT INTO #Tbl_UserDetails VALUES(104,5)
INSERT INTO #Tbl_UserDetails VALUES(105,3)
GO
SELECT ISNULL(Circle,'Total') Circle, ISNULL(COUNT([HeadCount]),SUM(1)) AS [Total]
FROM
(
SELECT DISTINCT 'Circle' = CASE
WHEN #Lkp_Circle.Abbreviation IN (SELECT Circle FROM #Lkp_OtherCircles) THEN #Lkp_Circle.Abbreviation
WHEN #Lkp_Circle.Abbreviation NOT IN (SELECT Circle FROM #Lkp_OtherCircles) THEN 'Others'
ELSE 'Total' END,ISNULL(#Tbl_UserDetails.AssociateID,0) AS 'HeadCount'
FROM #Tbl_User INNER JOIN #Tbl_UserDetails ON #Tbl_User.ID = #Tbl_UserDetails.AssociateID INNER JOIN
#Lkp_Circle ON #Tbl_UserDetails.CircleID = #Lkp_Circle.ID
WHERE #Tbl_User.IsActive='True' AND #Tbl_User.ID>0 AND #Tbl_UserDetails.AssociateID>0
) AS PivotTable
GROUP BY Circle
WITH Cube
DROP TABLE #Tbl_User,#Tbl_UserDetails,#Lkp_Circle,#Lkp_OtherCircles
----EXPECTED RESULT
--Circle HeadCount
--C3 2
--C4 1
--C5 2
--C6 0
--Others 0
--Total 5
--
----ACTUAL RESULT
--Circle HeadCount
--C3 2
--C4 1
--C5 2
--Total 5
The criteria for Others is that those circles which are not part of #Lkp_OtherCircles i.e. C1,C2,C3 and C7 clubbed together. I have tried checking for the condition ISNULL when for that circle there is no user but the end result is same. Can someone tell me where I am going wrong and how to correct it?
View 9 Replies
View Related
Nov 14, 2007
Hey guys,
This is what I think and hope is a fairly straight forward SQL question
Essentially, I have a table which has the following columns that are relevent to my question:
PROJID
ACTIVITY_NAME
COMPLETION_DATE
Rows in this table are, for example:
PROJID ACTIVITY_NAME COMPLETION_DATE
1 Prepro 10/12/2007 3:42:30
2 Prepro 10/13/2007 9:16:27
2 QA 10/13/2007 10:00:01
2 Delivery 10/14/2007 09:31:12
etc.
So, really the key is the PROJID & the ACTIVITY_NAME (really, there's a unique column ID, but for this question, I'll leave it at that).
(Though this should be much easier to accomplish in code, the system is not built that way so) Is there a good way that I could return a status for a given PROJID based on whether a row exists for a given PROJID). In other words, ultimately, I would like to return something like this:
PROJID LAST_ACTIVITY
----------------------------------------------
1 Prepro
2 Delivery
where the activity order (in this case) is Prepro, QA, Delivery. So because a Delivery row exists for PROJID 2, then the LAST_ACTIVITY would return "Delivery" and because only Prepro exists for PROJID 1, the LAST_ACTIVITY returned would be Prepro
I really appreciate the help
Thanks,
Steve
View 3 Replies
View Related
May 20, 2015
I have row group created here on Due Month & Sales Region & added total after Due Month. When a user clicks on particular amount I would like to send the Sales Region value to the new report as Parameter. So Instead of Total text , I would like to have all the sales regions concatenated and sent to the new report. writing an expression to get the report parameter? I have added the picture of how I want the values to be concatenated , instead of Total . Is this not possible in SSRS?
View 5 Replies
View Related
Dec 22, 2006
I have a stored procedure with a SELECT statement, that retrieves 1 row.
SELECT name FROM tblNames WHERE nameID = "1"
I want all the NULL values in that row to be change in some default values.
How do I do this?
View 4 Replies
View Related
Jan 11, 2007
I have a gridview that is based on the selection(s) in a listbox. The gridview renders fine if I only select one value from the listbox. I recive this error though when I select more that one value from the listbox:
Syntax error converting the nvarchar value '4,1' to a column of data type int. If, however, I hard code 4,1 in place of @ListSelection (see below selectCommand WHERE and IN Clauses) the gridview renders perfectly.
<asp:SqlDataSource ID="SqlDataSourceAll" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT DISTINCT dbo.Contacts.Title, dbo.Contacts.FirstName, dbo.Contacts.MI, dbo.Contacts.LastName, dbo.Contacts.Suffix, dbo.Contacts.Dear, dbo.Contacts.Honorific, dbo.Contacts.Address, dbo.Contacts.Address2, dbo.Contacts.City, dbo.Contacts.StateOrProvince, dbo.Contacts.PostalCode FROM dbo.Contacts INNER JOIN dbo.tblListSelection ON dbo.Contacts.ContactID = dbo.tblListSelection.contactID INNER JOIN dbo.ListDescriptions ON dbo.tblListSelection.selListID = dbo.ListDescriptions.ID WHERE (dbo.tblListSelection.selListID IN (@ListSelection)) AND (dbo.Contacts.StateOrProvince LIKE '%') ORDER BY dbo.Contacts.LastName">
<SelectParameters>
<asp:Parameter Name="ListSelection" DefaultValue="1"/>
</SelectParameters>
</asp:SqlDataSource>
The selListID column is type integer in the database.
I'm using the ListBox1_selectedIndexChanged in the code behind like this where I've tried using setting my selectparameter using the label1.text value and the Requst.From(ListBox1.UniqueID) value with the same result:
Protected Sub ListBox1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ListBox1.SelectedIndexChanged
Dim Item As ListItem
For Each Item In ListBox1.Items
If Item.Selected Then
If Label1.Text <> "" Then
Label1.Text = Label1.Text + Item.Value + ","
Else
Label1.Text = Item.Value + ","
End If
End If
Next
Label1.Text = Label1.Text.TrimEnd(",")
SqlDataSourceAll.SelectParameters("ListSelection").DefaultValue = Request.Form(ListBox1.UniqueID)
End Sub
What am I doing wrong here? Thanks!
View 4 Replies
View Related
May 1, 2007
Is there a way to retreive the SQL Statement with the values from the parameters merged together? I know how to retreive the SQL Select Statement and the parameters separately but I need to retreive the final SQL.
For example:
SELECT name FROM employee WHERE id = @id
I would like to retreive from SQLDataSource
SELECT name FROM employee WHERE id = 1
Thank you
View 4 Replies
View Related
May 16, 2005
If I try to run the code below, and even one of the values in the INNER
JOIN statements is NULL, the DataReader ends up with zero rows.
What I need is to see the results even if one or more of INNER JOIN
statements has a NULL value. For example, if I want info on
asset# 2104, and there's no value in the DriverID field, I need the
rest of the data to display and just have the lblDriverName by
blank. Is that possible?
<code>
Sub BindSearchGrid()
Dim searchUnitID As String
Dim searchQuery As String
searchUnitID = tbSearchUnitID.Text
lblIDNum.Text = searchUnitID
searchQuery = "SELECT * FROM Assets " & _
"INNER JOIN Condition ON Condition.ConditionID = Assets.ConditionID " & _
"INNER JOIN Drivers ON Drivers.DriverID = Assets.DriverID " & _
"INNER JOIN Departments ON Departments.DepartmentID = Assets.DepartmentID " & _
"INNER JOIN AssetCategories
ON AssetCategories.AssetCategoryID = Assets.AssetCategoryID " & _
"INNER JOIN Store ON
Store.[Store ID] = Assets.StoreID WHERE RTRIM(Assets.[Unit ID]) = '"
& searchUnitID & "'"
Dim myReader As SqlDataReader
myReader = Data.queryDB(searchQuery)
While myReader.Read
If
Not IsDBNull(myReader("Store Name")) Then lblStrID.Text =
myReader("Store Name")
If
Not IsDBNull(myReader("AssetCategory")) Then lblAsstCat.Text =
myReader("AssetCategory")
If
Not IsDBNull(myReader("Condition Description")) Then lblCondID.Text =
myReader("Condition Description")
If
Not IsDBNull(myReader("DepartmentName")) Then lblDepID.Text =
myReader("DepartmentName")
If
Not IsDBNull(myReader("Unit ID")) Then lblUnID.Text = myReader("Unit
ID")
If
Not IsDBNull(myReader("Year")) Then lblYr.Text = myReader("Year")
If
Not IsDBNull(myReader("Make")) Then lblMk.Text = myReader("Make")
If
Not IsDBNull(myReader("Model")) Then lblMod.Text = myReader("Model")
If
Not IsDBNull(myReader("Mileage")) Then lblMile.Text =
myReader("Mileage")
If
Not IsDBNull(myReader("Vin Number")) Then lblVinNum.Text =
myReader("Vin Number")
If
Not IsDBNull(myReader("License Number")) Then lblLicNum.Text =
myReader("License Number")
If
Not IsDBNull(myReader("Name")) Then lblDriverName.Text =
myReader("Name")
If
Not IsDBNull(myReader("DateAcquired")) Then lblDateAcq.Text =
myReader("DateAcquired")
If
Not IsDBNull(myReader("DateSold")) Then lblDtSld.Text =
myReader("DateSold")
If
Not IsDBNull(myReader("PurchasePrice")) Then lblPrPrice.Text =
myReader("PurchasePrice")
If
Not IsDBNull(myReader("NextSchedMaint")) Then lblNSM.Text =
myReader("NextSchedMaint")
If
Not IsDBNull(myReader("GVWR")) Then lblGrVWR.Text = myReader("GVWR")
If
Not IsDBNull(myReader("GVW")) Then lblGrVW.Text = myReader("GVW")
If
Not IsDBNull(myReader("Crane Capacity")) Then lblCrCap.Text =
myReader("Crane Capacity")
If
Not IsDBNull(myReader("Crane Certification")) Then lblCrCert.Text =
myReader("Crane Certification")
If
Not IsDBNull(myReader("Repair Cost")) Then lblRepCost.Text =
myReader("Repair Cost")
If
Not IsDBNull(myReader("Estimate Replacement")) Then lblEstRep.Text =
myReader("Estimate Replacement")
If
Not IsDBNull(myReader("SalvageValue")) Then lblSalVal.Text =
myReader("SalvageValue")
If
Not IsDBNull(myReader("CurrentValue")) Then lblCurVal.Text =
myReader("CurrentValue")
If
Not IsDBNull(myReader("Comments")) Then lblCom.Text =
myReader("Comments")
If
Not IsDBNull(myReader("Description")) Then lblDesc.Text =
myReader("Description")
End While
End Sub</code>
View 1 Replies
View Related
Jul 20, 2005
Hi,I have boolean values in a table for ex. Federation. And I want toselect followingSelect 'Insert into' + member + 'test' as test1from federationThen I get error messageServer: Msg 403, Level 16, State 1, Line 1Invalid operator for data type. Operator equals add, type equals bit.Someone can help me out of it.Thanks an advance- Loi -
View 3 Replies
View Related
Nov 22, 2013
I have two tables I am working with, they are "Institutions" and "InstitutionOversights". The relationship is one-to-many.
The sample data is below.
Table one:
InstitutionID, InstName
------------------------
1 School Alpha
2 School Beta
3 School Charlie
4 School Delta
Table two:
InstitutionOversightID, InstitutionID, Type
------------------------------------------------
1 1 Accreditation
2 1 Verifcation
3 1 Old System
I would like a query to return the results in the following format:
InstitutionID, InstName, TypeList
-----------------------------------------------
1 School Alpha Accreditation, Verification, Old System
2 School Beta null
3 School Charlie null
4 School Delta null
View 3 Replies
View Related
Jun 4, 2007
Hello to all,
i have a problem with IN-Operator. I cann't resolve it. I hope that somebody can help me.
I have a IN_Operator sql query like this, this sql query can work. it means that i can get a result 3418:
declare @IDM int;
declare @IDO varchar(8000);
set @IDM = 3418;
set @IDO = '3430'
select *
from wtcomValidRelationships as A
where (A.IDMember = @IDM) and ( @IDO in (3428 , 3430 , 3436 , 3452 , 3460 , 3472 , 3437 , 3422 , 3468 , 3470 , 3451 , 3623 , 3475 , 3595 , 3709 , 3723 , 3594 , 3864 , 3453 , 4080 ))
but these numbers (3428 , 3430 , 3436 , 3452 , 3460 , 3472 , 3437 , 3422 , 3468 , 3470 , 3451 , 3623 , 3475 , 3595 , 3709 , 3723 , 3594 , 3864 , 3453 , 4080 ) come from a select-statement. so if i use select-statement in this query, i get nothing back. this query like this one:select *
from wtcomValidRelationships as A
where (A.IDMember = @IDM) and ( @IDO in (select B.RelationshipIDs from wtcomValidRelationships as B where B.IDMember = @IDM))
I have checked that man can use IN-Operator with select-statement. I don't know why it doesn't work with me. Could somebody help me? Thanks
I use MS SQL 2005 Server Management Stadio Express
Thanks a million and Best regards
Sha
View 2 Replies
View Related
Feb 4, 2014
I wrote a select statement, I only want to see orders with max lastUpdatedOn date of 14 days and older. Now my results show dates with all orders of 14 days and older (which is OK), but all others are displayed in the "Uitgifte" column as "NULL". But those orders should not be displayed at all.
selectdistinct ProductionHeader.ProdHeaderOrdNr,
ProductionHeader.PartCode,
ProductionHeader.Description,
ProductionHeader.Qty,
(select max (ProdStatusLog.ProdStatusCode)
[code]...
View 8 Replies
View Related
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
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