How To Aggregate A Column By Concatenation

Mar 28, 2012

How do I aggregate a column by concatenation?

/*
SQL Server 2000 datbase

I have 3 tables.
A "client" table.
A "call history" table.
And a "call detail" table.

The "client" table contains data about individual clients.
The "call history" table contains data about calls to or from the clients in the "client" table. (This is a one-to-many relationship of client-to-history interactions.)
The "call detail" table contains detail data about a particular "call history" entry. (This is also a one-to-many relationship of history-to-detail entries.)
*/

Code:

DECLARE @Client TABLE (ClientID INT PRIMARY KEY, ClientName VARCHAR(100))
INSERT INTO @Client
SELECT 1 [ClientID], 'Client A' [ClientName]
UNION ALL SELECT 2, 'Client B'
UNION ALL SELECT 3, 'Client C'
UNION ALL SELECT 4, 'Client D'
SELECT c.ClientID, c.ClientName

[Code]....

View 5 Replies


ADVERTISEMENT

Concatenation Aggregate

Nov 17, 2007

Are we actually going to get a string concatenation aggregate in SQL Server 2008?? I am so sick of having to write a UDF for every concatenation I want to do. I am well aware of all the methods available to do it now, and they are all junk, and the performance is horrible. I'm sure it is a challenging problem, and there are known pitfalls, but its time to address these.

The notion that it is the responsibility of the front end to do the concatenation is pure bs. You don't dump 10,000 rows to your report server when you only need to display 1000, just so you can concatenate one lousy column.


I want to be able to write:

SELECT CustName, SUM(ProductPrice), CONCAT(ProductName, [my separator], ORDER OVER ProductName ASC)
FROM Orders

And I'm not going to stop complaining til I get it! (-;



View 4 Replies View Related

Aggregate String Concatenation

Oct 3, 2005

I have the following data:

create table TempTable(name varchar(50), value varchar(50))
insert into temptable values ('A', 'one')
insert into temptable values ('A', 'two')
insert into temptable values ('A', 'three')
insert into temptable values ('B', 'four')
insert into temptable values ('B', 'five')

and i would like the following output:

'A', 'one, two, three'
'B', 'four, five'

any ideas on how to accomplish this in Sql Server 2000?

thx in advance..

View 1 Replies View Related

Aggregate Concatenation In SQL 2000 Vs 2005

Dec 10, 2007

I have created a UDF in SQL 2000 to implement a String Concatenation in an aggregate query. It works fine, but with the large data set I am using this against, it is very SLOW. (I also tried using a Cursor in a SP but that was even slower!)

I have seen several articles on the web about performing aggregate concatenation in SQL Server 2005 using either the PIVOT function, XML, or the Common Language Runtime (CLR).

Does anyone know how much better these statements perform in SQL 2005 over the method I am using in SQL 2000? If it is significantly higher performing in 2005 this may push us to upgrade our system to use it.

Thanks,
Mike

View 9 Replies View Related

Column Name Alias Concatenation

Feb 20, 2004

I have a web application where I would like to return a dynamic column name using aliasing. below is an example:

select hours as 'Fri<BR>' + cast(Day(getDate()) as varchar(2)) from todayshours

I get an error trying to do concatenation as part of the alais. Any ideas?

Luke
lgraunke AT 4invie.com

View 4 Replies View Related

T-SQL (SS2K8) :: Create Column Alias With Concatenation?

Sep 16, 2014

I want to create column name dynamically in select list.

create table #temp(name varchar(10), sale int)
insert into #temp values('john',1000)
insert into #temp values('Mike',500)
insert into #temp values('Abhas',200)
select name,sale as sale from #temp

Now i want change column alias only , not value. I need to concatenate sale with year value of getdate(). i.e. column header concatenation only, not a output value.

so my output would be as

name Sales2014
john 1000
Mike 5000
Abhas 2000

View 4 Replies View Related

How To Aggregate A Column That Was Itself An Aggregate

Jul 15, 2005

I have a column that has an expression with a runningvalue in it, a "Carrying Cost" for each month. I need to create another column that aggregates the monthly Cost. I can't to do a Runningvalue on the Runingvalue. I can't even do a Sum on the Runningvalue.

View 9 Replies View Related

Integration Services :: Conditional Concatenation In Derived Column?

Aug 3, 2015

I have 10 columns i.e from Segment1 to Segment10. I need to concatenate it with ".". All 10 segments can be null. If any of the segment is null i do not want to show ".". This is the expression I am using

 (DT_STR,100,1252)((ISNULL(SEGMENT1) ? "" : "." + SEGMENT1) + (ISNULL(SEGMENT2) ? "" : "." + SEGMENT2) + (ISNULL(SEGMENT3) ? "" : "." + SEGMENT3) + (ISNULL(SEGMENT4)
? "" : "." + SEGMENT4) + (ISNULL(SEGMENT5) ? "" : "." + SEGMENT5) + (ISNULL(SEGMENT6) ? "" : "." + SEGMENT6) + (ISNULL(SEGMENT7) ? "" : "." + SEGMENT7)
+ (ISNULL(SEGMENT8) ? "" : "." + SEGMENT8) + (ISNULL(SEGMENT9) ? "" : "." + SEGMENT9) + (ISNULL(SEGMENT10) ? "" : SEGMENT10))

But if any of the column contains Null or Blank I get ...... I do not want to show these .... if any segment is null.

What mistake am I doing in the above expression?

View 4 Replies View Related

Query To Find A Value In Column B Based On An Aggregate Function On Column A?

Jul 20, 2005

Hi,Suppose I have a table containing monthly sales figures from my shopbranches:Branch Month Sales-----------------------London Jan 5000London Feb 4500London Mar 5200Cardiff Jan 2900Cardiff Feb 4100Cardiff Mar 3500The question I am trying to ask is this: in which month did each branchachieve its highest sales? So I want a result set something like this:Branch Month----------------London MarCardiff FebI can do a "SELECT Branch, MAX(Sales) FROM MonthlySales GROUP BY Branch" totell me what the highest monthly sales figure was, but I just can't figureout how to write a query to tell me which month corresponded to MAX(Sales).Ideas anyone?Cheers,....Andy

View 5 Replies View Related

Integration Services :: Derived Column Transformation - Concatenation Of Two Fields

Jun 4, 2015

I have the following 2 fields that are sourced from an Excel spreadsheet

DocNumber - a 10 digit number
PostingRow - a number between 1 and 999

I would like to produce a new column that is a concatenation of these two fields, but the PostingRow needs to be a 3 digit number eg. 1000256153-001 ....

View 7 Replies View Related

Aggregate Bitwise OR On A Column

Oct 22, 2014

I am trying to get a culmulative Bitwise OR operation on a column by query - rather than using a CLR function.

The problem is shown below:

CREATE TABLE #Operations (
PK INT NOT NULL IDENTITY(1,1),
UserName VARCHAR(50) NOT NULL,
UserProcess VARCHAR(50) NOT NULL,
ServerOperation VARCHAR(50) NOT NULL,
Permission INT NOT NULL );

[Code] ....

So Far I've tried SUM - wrong results, and STUFF - which doesn't seem appropriate for bitwise operation - neither give useful results.

-- SUM Operation - fails
SELECT DISTINCT
UserName,
ServerOperation,
SUM(Permission) AS Permission
FROM #Operations

[Code] ....

It may be possible to materialise the permissions each time one is changed (e.g. by to use a cursor ), however I would prefer a query or function or combination to generate the result.

View 5 Replies View Related

Aggregate (SUM) A Column And Then Use The Result?

May 7, 2007

Hi,



I am importing some data from Excel. I have to SUM one of the columns, and then use the result of the sum to calculate the percentages of each row. How can I use the Aggregate to give me a total of a column, so that i can use the total in another task and use formulas to calculate the percentages? i have tried to use multicast and join, but I get an extra row with the sum, which is not what I want; I want to use the sum for all the data.



Thanks

View 9 Replies View Related

Selecting The Corresponding Column Value When Using Min Or Max Aggregate.

May 4, 2007

Greetings,

I have a dataset something like this:



Loc Value Time
A 3 1AM
A 8 2AM
A 2 3AM
A 1 4AM
...
B 8 1AM
B 1 2AM
...

When we collapse the Loc group I want to show the Max vlaue and the time it
occurred.



A 8 2AM
B 8 1AM



What is the expression for the Time column of the table to ensure
the time of the maximum value is shown?

Thanks

View 8 Replies View Related

Aggregate Column Comparison In Sql Server Sql ?

Jul 27, 2005

I am no expert in sql, but I keep stubbling on this problem:I have a table t1 with 2 columns (a,b)I have a table t2 with 2 columns (c,d)I need to delete all records from t1 which have the same value (a,b)than the value of (c,d) in all records in the t2 table.I oracle, this is simple:delete from t1where (a,b) in (select c,d from t2)because Oracle has support for this syntax. Dont remember how they callit. But this is not support in sql server. So I have to resort to:delete from t1where a + '+' + b in ( select c + '+' + d from t2)Of course, a,b,c,d must be varchar for this to work. Basically I fake aunique key for the records. Is there a better way to do this?Thanks

View 3 Replies View Related

How To Get Aggregate Column From Joined Table

Feb 6, 2008

Can someone please help me with a better way to format the following query. This works, but I know it is hidious.






Code Snippet

select

convert(varchar, processed, 101) as Date,
count(o.id) as [# Orders],
sum(distinct a.runnercount) as [# Runners],
sum(o.total) as [$ Gross],
sum(o.fee) as [$ Fees],
(sum(o.total)-sum(o.fee)) as [$ Net]

from [order] o join (select convert(varchar,processed,101) as date, count(*) as runnercount from orderitem oi inner join [order] o on o.id = oi.orderid where typeofextraid = 4 group by convert(varchar,processed,101)) a on convert(varchar,processed,101) = a.date

where statemented = @statemented
group by convert(varchar, processed, 101)
2 tables: Order and OrderItem. I need the sum of a specific record type from the OrderItem table along with all the other aggregate columns group by day.

Thanks.

Nathan

View 1 Replies View Related

T-SQL (SS2K8) :: Create Sequential Aggregate Of A Column Using Sum?

Aug 17, 2015

create a sequential aggregate of a column using sum in tsql.

I want a column that will sum up all hours work by transaction date.

for example

Monday my hours work will be 8 and therefore my total transaction hours will be 8.

Tuesday my hours work will be 8 but I want the total hours of my total transaction hours to 16.

Wed my total hours work will be 5 and I want the total hours of my total transaction hours to 21. etc.

Select myname, weekday, hours worked, Totalhours_ToDate =Sum(hours worked) from table

View 5 Replies View Related

Transact SQL :: Create Sequential Aggregate Of A Column Using Sum?

Aug 17, 2015

I need to create a sequential aggregate of a column using sum in tsql.

I want a column that will sum up all hours work by transaction date.

for example

Monday my hours work will be 8 and therefore my total transaction hours will be 8.

Tuesday my hours work will be 8 but I want the total hours of my total transaction hours to  16.

Wed my total hours work will be 5 and I want the total hours of my total transaction hours to  21. etc.

Select myname, weekday, hours worked, Totalhours_ToDate =Sum(hours worked)from table

View 3 Replies View Related

Sending Column Name As A Parameter To Aggregate Function

Jul 29, 2006

How can do this. Because my stored function contains same clause except colums name.So I want to use column name as a parameter but how can send column name and use it like Sum(parameter) function .

my procedure like this:

ALTER PROCEDURE [dbo].[ORNEK10]

@YIL VARCHAR(4),

@TEKLIF_TURU VARCHAR(255)

AS

BEGIN

DECLARE @N1 FLOAT

DECLARE @N2 FLOAT

SET @N1 = ( SELECT DEGERI FROM PARAMETRE WHERE PARAMETRE_ADI='N1')

SET @N2 = ( SELECT DEGERI FROM PARAMETRE WHERE PARAMETRE_ADI='N2')

SET NOCOUNT ON;

--I want to avoid using if statements for Sum() function

IF(@TEKLIF_TURU='BASKAN_TEKLIF')

SELECT TOP (100) PERCENT KOD1, KOD2, KOD3, KOD4, dbo.ORNEK10AD(KOD1, KOD2, KOD3, KOD4) AS ACIKLAMA,

SUM(BASKAN_TEKLIF) AS YILI,

((100+@N1)*SUM(BASKAN_TEKLIF))/100 AS YIL1,

((100+@N1)*(100+@N2)*SUM(BASKAN_TEKLIF))/10000 AS YIL2

FROM GELIR AS G WHERE YIL = @YIL GROUP BY KOD1, KOD2, KOD3, KOD4 WITH ROLLUP

ORDER BY KOD1, KOD2, KOD3, KOD4

IF(@TEKLIF_TURU='ENCUMEN_TEKLIF')

SELECT TOP (100) PERCENT KOD1, KOD2, KOD3, KOD4, dbo.ORNEK10AD(KOD1, KOD2, KOD3, KOD4) AS ACIKLAMA,

SUM(ENCUMEN_TEKLIF) AS YILI,

((100+@N1)*SUM(ENCUMEN_TEKLIF))/100 AS YIL1,

((100+@N1)*(100+@N2)*SUM(ENCUMEN_TEKLIF))/10000 AS YIL2

FROM GELIR AS G WHERE YIL = @YIL GROUP BY KOD1, KOD2, KOD3, KOD4 WITH ROLLUP

ORDER BY KOD1, KOD2, KOD3, KOD4



IF(@TEKLIF_TURU='MECLIS_TEKLIF')

SELECT TOP (100) PERCENT KOD1, KOD2, KOD3, KOD4, dbo.ORNEK10AD(KOD1, KOD2, KOD3, KOD4) AS ACIKLAMA,

SUM(MECLIS_TEKLIF) AS YILI,

((100+@N1)*SUM(MECLIS_TEKLIF))/100 AS YIL1,

((100+@N1)*(100+@N2)*SUM(MECLIS_TEKLIF))/10000 AS YIL2

FROM GELIR AS G WHERE YIL = @YIL GROUP BY KOD1, KOD2, KOD3, KOD4 WITH ROLLUP

ORDER BY KOD1, KOD2, KOD3, KOD4

END

View 4 Replies View Related

SQL Server 2012 :: Updated Aggregate Column Where Value Is A Rolling Sum

Apr 29, 2014

I am trying to create an aggregate table where the value is a rolling sum. Type a on date 1 is the sum of the values in the main tbl. Type a on date 2 is the sum of values for type a on date 1 and date 2. Is this possible? I have been trying update t sql with sum(case where date <= date) statements but can't get it to run.

create table main_table (type nvarchar(10), date int, datavalues int);
insert into main_table
values('a', '1',3);
insert into main_table
values('b', '1',4)

[Code] .....

View 9 Replies View Related

Aggregate Functions - Adding Extra Column With Another Field

Jun 13, 2014

I have a simple query like:

select max(PTR_DATE)
from MPR_portfolio_transactions
group by PTR_SYMBOL

and this is working fine, but if I add an extra column with another field like:

select max(PTR_DATE) , PTR_SHAREBALANCE
from MPR_portfolio_transactions
group by PTR_SYMBOL

Then I get an error message like:

Column 'MPR_portfolio_transactions.PTR_SHAREBALANCE' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

How can I get round to this?

View 6 Replies View Related

Cannot Find Either Column Dbo Or The User-defined Function Or Aggregate Dbo.FN_NIVELCOMPETENCIACARGO, Or The Name Is Ambiguo

May 4, 2006

Hello i have this query and I havent been able to solve it

Cannot find either column "dbo" or the user-defined function or aggregate "dbo.FN_NIVELCOMPETENCIACARGO", or the name is ambiguous.

I have tried with dbo and withou dbo, specifyng columns inside it,



Thanks

select a.nmempresa,a.nmtipocompetencia, d.dsnombreciclo, c.dsnombrecargo,a.dstipocompetencia, a.dscatalogo,

b.popeso as PesoTipoCompetencia, f.dsnombrecompetencia as Competencia, e.pocompetencia as PesoCompetencia,

g.DSOPCIONESCALA, g.PESO

from

tgsc_tiposcompetencias a, TGSC_TIPOSCOMPETENCIASxcargo b, tgsc_cargos c, tgsc_ciclos d,

tgsc_competenciasxcargo e, tgsc_competencias f,

(select

dbo.FN_NIVELCOMPETENCIACARGO(a.nmempresa,a.nmciclo, a.nmtipocompetencia,c.nmcargo,f.nmcompetencia)) as g

where a.nmempresa=72 and a.nmciclo=9

and b.nmtipocompetencia=a.nmtipocompetencia

and b.nmcargo=10 and b.nmempresa=72 and b.nmciclo=9

and c.nmcargo=10 and c.nmempresa=72 and c.nmciclo=9 and d.nmciclo=9

and e.nmcargo=10 and e.nmciclo=9 and e.nmempresa=72

and f.nmcompetencia=e.nmcompetencia and f.nmtipocompetencia=a.nmtipocompetencia

and f.nmtipocompetencia=b.nmtipocompetencia

View 7 Replies View Related

SQL Server 2012 :: Column X Is Invalid In Select List Because It Is Not Contained In Aggregate Function

Apr 3, 2015

I have a specific variation on the standard 'Column Invalid' question: I have this query that works fine:

SELECT vd.Question ,
csq.Q# ,
csq.Q_Sort ,
csq.Q_SubSort ,
AVG(CAST(vd.Response AS FLOAT)) AS AvgC ,
vd.RType

[Code] ....

When I add this second average column like this:

SELECT vd.Question ,
csq.Q# ,
csq.Q_Sort ,
csq.Q_SubSort ,
AVG(CAST(vd.Response AS FLOAT)) AS AvgC ,

[Code] ....

I get the error: Column 'dbo.vwData.Response' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

Clearly things are in the right place before the change, so I can only assume that the OVER clause is my problem. Is this just not possible?

View 1 Replies View Related

Cannot Perform An Aggregate Function On An Expression Containing An Aggregate Or A Subquery.

Oct 19, 2007

Can any1 tell me why i am getting an error


SELECT DISTINCT

--p.voucher,

--p.amount,

p.siteID,

b.siteID,

SUM((round(b.total,2,2)) - SUM(round(p.amount,2,2))) AS OutStandingBalance,

SUM((round(b.total,2,2)) - SUM(round(p.amount,2,2))) AS CashCheque,

SUM((round(b.total,2,2)) - SUM(round(p.amount,2,2))) AS Vouchers

FROM

BillingTotal b,

Payment p

--WHERE

-- s.sitename=@cmb1

--AND p.siteid = s.siteid

-- p.voucher = 0

-- p.voucher = 1

GROUP BY p.siteID,b.siteID



Msg 130, Level 15, State 1, Line 1

Cannot perform an aggregate function on an expression containing an aggregate or a subquery.

View 8 Replies View Related

Analysis :: Calculated Member From Aggregate And Non-aggregate Factors

Sep 22, 2015

I have 2 Dimensions in SSAS (see below end), I want to create a calculated member, named

This_Year_Billable_Objective_Count, with its formula = BillableLastYear*(100+ BillableObjective)/100.

The first factor,  BillableLastYear is a number, aggregated (sum) from child units.

The second factor,  BillableObjective is a percent number (for example 28 means 28%), it's not aggregate. It's an dependent value for each unit.

How can I calculate This_Year_Billable_Objective_Count for each unit?

\ able 1
SELECT [UnitKey]
      ,[UnitID]
      ,[UnitName]
      ,[Unit2Name]
      ,[Unit3Name]
      ,[Unit4Name]

[Code] .....

View 6 Replies View Related

Concatenation

Jun 12, 2008

I need to concatenate two date fields so they appear in a drop-down list like this:   8:00 AM - 10:00 AM
I'm using MS SQL 2005 and my query looks like this:  SELECT ClinicTimesID, ClinicID, (CTStartTime + ' - ' + CTEndTime) AS TimeSlot FROM Clinics_Times WHERE (ClinicID = 1) and I get this error:  Msg 242, Level 16, State 3, Line 1
The conversion of a char data type to a datetime data type resulted in an out-of-range datetime value.
Can I strip out the date so that only the time appears or is it even possible to concatenate these fields?  If so, how?
Thanks!

View 1 Replies View Related

Concatenation

Sep 8, 2005

Hello all, I'm trying to combine two columns of data into a third column using a formula on the thrid column. Each of the columns could contain nulls and each of the columns could contain padding after or before the data. I'm trying to use the following formula yet SQL is throwing an error. Can someone provide another set of eyes to check this out? ISNULL(LTRIM(RTRIM([user_Define_4a])),’’) + ISNULL(LTRIM(RTRIM([user_Define_1])),’’) Thanks

View 2 Replies View Related

DTS Concatenation - Please Help

Nov 17, 1999

I am importing via DTS a .csv file. I have 2 issues:

-One field from the source needs to be inserted into two existing fields.

-Two fields from the source, First_Name and Last_Name need to be
concatenated to a destination field, Full_Name.

I do not know VB but I do know SQL.

Can anyone help?

View 1 Replies View Related

Concatenation

Mar 7, 2007

Hi. I want to make a query that concatenate the address of the person with a comma inbetween and neglecting the null value.

table - pspersonaldata
dcno name streetbldg1 streetbldg2 streetbldg3
1 jon santol1 null santol3
2 mike mangga1 mangga2 null
3 jay langka1 langka2 langka3
4 joy null buko2 buko3
5 jean null null null

expected output is:

name address
jon santol1, santol3
mike mangga1, mangga2
jay langka1, langka2, langka3
joy buko2, buko3
jean null

thanks.
-Ron-

View 14 Replies View Related

Concatenation

Oct 3, 2007

I am completely new to SQL and I have some syntax questions. I am trying to concatenate 4 fields and some padded constants to form a new key field to perform joins. The result should be a twelve character field without spaces. My problem is that the current fields use spaces as place holders and I need to replace the spaces with ‘0’.

[RD_ID] nvarchar length 5
[RDWY_ID] nvarchar length 1
[MLGE_TYPE] nvarchar length 1
[OVLAP_MLGE_CD] nvarchar length 1

Concatenate 12 characters

1st ‘0’ (constant)
2nd, 3rd, and 4th, from [RD_ID] (without the suffix)
5th and 6th from [RD_ID] suffix or replace spaces with ‘00’
7th 1 or 2 from [RDWY_ID]
8th Z from [MLGE_TYPE] or replace space with ‘0’
9th 1 – 9 from [OVLAP_MLGE_CD] or replace space with ‘0’
10th ‘S’ (constant)
11th ‘0’ (constant)
12th ‘0’ (constant)

Results should resemble
0001CQ100S00 or 000100100S00

This is the query I used in Access.

LRS: "0" & IIf((Len(LTrim(RTrim([HITIS2_TVCLEAR2]![RD_ID])))=3),LTrim(RTrim([HITIS2_TVCLEAR2]![RD_ID])) & "00",LTrim(RTrim([HITIS2_TVCLEAR2]![RD_ID]))) & [HITIS2_TVCLEAR2]![DIR_RDWY_ID] & IIf([HITIS2_TVCLEAR2]![MLGE_TYPE]=" ",0,[HITIS2_TVCLEAR2]![MLGE_TYPE]) & IIf([HITIS2_TVCLEAR2]![OVLAP_MLGE_CD]=" ",0,[HITIS2_TVCLEAR2]![OVLAP_MLGE_CD]) & "S00"

Thanks for any help.

View 6 Replies View Related

Concatenation

Feb 27, 2008



My file is in this format

Col1 Col2 Col3
---------------------------------------------------------------------------
Andrews S 93845877712 P
Sylvia 9999876669 J
Bill K 7657654677 L

I need the output like this
Col1 Col2 Col3
--------------------------------------------------------------------------
AndrewsS 93845877712 P
Sylvia 99999876669 J
BillK 76576546677 L

The character on the left of Col2 has to be joined to Col1 and character on the right of col2 has to be joined to Col3. Can anybody suggest a query for this.

Thanks,

View 3 Replies View Related

Concatenation

Apr 8, 2008



I need to concatenate the strings of the grouped result set in my report. Lets say if I have

ID Text
-----------------
1 text1
1 text2
1 text3


and if I am grouping by ID, the resulted text should be "text, text2, text3". Any ideas on this? Its kind of emergency

Thanks
Dinesh

View 5 Replies View Related

Dynamic SQL - Concatenation!

May 1, 2008

Hi All,
I've been trying to create a dynamic query using the 'Like' clause and '%'.
my code snippet looks like this:
while (@@FETCH_STATUS = 0)begin   set @likeString = @likeString + ' item_Text LIKE ''%'+@word+'%'' OR '   fetch next from theLike   into @word end
 
-- strip off last ORset @likeString = ltrim(rtrim(substring(@likeString, 0, (len(@likeString) - 3))))-- ================================================-- create query to find keywords in the index and store in temp table-- ================================================set @query = 'INSERT into #resulttable (itemcount, item_id) SELECT COUNT(d.item_id), d.item_id FROM tp_index_details AS d INNER JOIN tp_index ON d.idx_id = tp_index.idx_id 'set @query = @query +' WHERE (d.idx_id IN (SELECT idx_id FROM tp_index AS i WHERE ( 'set @query = rtrim(@query) + @likeStringset @query = @query + ' ) AND (subscription_id = 1000))) GROUP BY d.item_id ORDER BY d.item_id DESC'
The problem is the @query string gets truncated. My question is how to get the quotes around '%' variables to work in a string?
Thanks for any help!
regards
Davej

View 4 Replies View Related

SQL And Proper Concatenation Within VB

Jun 9, 2008

Hi all - I have posted inquiries on this rather vexing issue before, so I apologize in advance for revisting this. I am trying to create the code to add the parameters for two CheckBoxLists together. One CheckBoxList allows users to choose a group of Customers by Area Code, the other "CBL" allows users to select Customers by a type of Category that these Customers are grouped into. When a user selects Customers via one or the other CBL, I have no problems. If, however, the user wants to get all the Customers from one or more Area Codes who ALSO may or may not be members of one or more Categories; I have had trouble trying to create the proper SQL. What I have so far:Protected Sub btn_CustomerSearchCombined_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btn_CustomerSearchCombined.Click        Dim CSC_SqlString As String = "SELECT Customers.CustomerID, Customers.CustomerName, Customers.CategoryID, Customers.EstHours, Customers.Locality, Category.Category FROM Customers INNER JOIN Category ON Customers.CategoryID = Category.CategoryID WHERE "        Dim ACItem As ListItem        Dim CATItem As ListItem        For Each ACItem In cbl_CustomersearchAREA.Items            If ACItem.Selected Then                CSC_SqlString &= "Customers.AreaCodeID = '" & ACItem.Value & "' OR "            End If        Next        CSC_SqlString &= "' AND " <-- this is the heart of my problem, I believe        For Each CATItem In cbl_CustomersearchCAT.Items            If CATItem.Selected Then                CSC_SqlString &= "Customers.CategoryID = '" & CATItem.Value & "' OR "            End If        Next        CSC_SqlString = Left(CSC_SqlString, Len(CSC_SqlString) - 4)        CSC_SqlString &= "ORDER By Categories.Category"        sql_CustomersearchGrid.SelectCommand = CSC_SqlString    End SubAny help on this is much appreciated, many thanks -- 

View 5 Replies View Related







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