Fast Way To Concat Records To Comma Sep VARCHAR
Jul 20, 2005
Hi All,
Here's a challenge.
If there is a 'one word' answer to this, i.e. the name of a built in
SQL Server function I can use, that would be great! However...
I have a standard 1:m relationship, e.g. tblHeader and tblDetail.
I want to create a view of records from 'tblHeader' and within that
view have a column (called e.g. DetailTypes) that provides a single
comma separated varchar of values from a varchar field (called e.g.
DetailType) that appears in related records in the 'tblDetail' table.
(hope you understood that :)
e.g. the contents of my 'tblDetail' table could be....
Detail ID | Header ID | DetailType
-----------------------------------
1 | 1 | A
2 | 1 | A
3 | 1 | B
4 | 2 | A
5 | 2 | C
6 | 3 | B
Therefore, the view I want to create should return:
Header ID | DetailTypes
-------------------------------
1 | 2A, 1B
2 | 1A, 1C
3 | 1B
i.e. the first row can be read as "Header 1 has 2 'A' detail records
and 1 'B' detail record."
I have created a view e.g. 'vqryHeaders' which calls a user defined
function that takes the HeaderID and opens a cursor on another view,
e.g. 'vqryDetailGrouped'. The other view groups the records in
tblDetail so that I can get a count of each DetailType for each Header
ID. The cursor then loops through the returned records concatenating
the count and detail type into a comma separated string (as shown
above).
However, when I run this across 20k records it is soooo sloooooww. I
have indexes on the relationship fields and I am using realistically
sized varchars - neither made any difference in speed. It is
definately the function that I wrote that slows it down as the view is
lightning fast when I remove my function call.
I can supply source code if necessary, but I think that this is a
kind-of generic problem so I don't see the point - yet.
I really hope you can help.
Regards,
Jezz
View 11 Replies
ADVERTISEMENT
Nov 25, 2007
Hi,
I try to create a string that represant a insert statement but I've some problems to concat :
Set @Insert = 'INSERT INTO DEMANDES VALUES (' + @AvionID + ',' + @DemandeID + ',' + @Consommation + ',' + @Vitesse + ',' + @TailleReservoire + ',''' + @PlageHoraireDebut +''','''+ @PLageHoraireFin+''','''+ @VilleDepart+''',''' +@VilleDestination+''');';
AvionID is a int
DemandeID too
Consommation too
Vitesse too,
TailleReservoire too,
PlageHoraire varchar and ville too.
Can you explain me how to concat these strings?
Thanks for your help!
View 5 Replies
View Related
Dec 7, 2006
Hi all. I have been going round and round for the past 2 days on this and would appreciate any help. In a view select statement, I need to concat 2 varchar fields with a text field. If I CONVERT the TEXT field to VARCHAR, only the first 30 characters of the field appear in the result set. If I convert the VARCHAR fields to TEXT, I get an error that I cannot CONCAT TEXT fields. I'm not sure what to do. Can someone please offer some assistance? Thanks in advance! Steve
View 1 Replies
View Related
Mar 6, 2006
I have a table containing URLs. I want to be able to look up an URL veryfast, so I used an nvarchar to store the URL, and put an index on it(maybe naive).Anyway, I bump into:"The index entry of length 911 bytes for the index 'UQ__URL__1367E606'exceeds the maximum length of 900 bytes."What's the best way to handle this? I want to do the look up fast. Theonly thing I could think up was adding an extra column containing a digestfor the URL, and look up all URLs with the same digest, *and* having thesame value (which could give either 1 or 0 results).I am new to MS SQL, so I might describe a silly solution, basically I wantto look up URLs to ID the fastest way possible.--John MexIT: http://johnbokma.com/mexit/personal page: http://johnbokma.com/Experienced programmer available: http://castleamber.com/Happy Customers: http://castleamber.com/testimonials.html
View 3 Replies
View Related
Jul 20, 2005
I seem to remember reading many moons ago about a function where youcan retrieve a count of the last recordset you opened.For example:I've got a stored procedure that returns a recordset using the TOP 10so I only get the top 10 records. I need to know the recordcount but Idont want to reuse the SELECT statement because its quite complex.Any ideas?What does @@Count do?Thanks in advance
View 1 Replies
View Related
Feb 14, 2015
Below is my sample data and query
declare @Sample table (ID int, message varchar(1000))
insert into @Sample(ID,message)
select 1,'Testing 1' union all
select 1,'Testing 2' union all
select 1,'Testing 3' union all
[Code] ....
I need to get top three values has to be comma separated. for example id 1 has 5 rows message which comma separated. Instead i need to consider top three message group by Id
expected result :
IDmessage
1Testing 1, Testing 2, Testing 3
2Testing 6, Testing 7, Testing 8
3Testing 11, Testing 12, Testing 13
View 3 Replies
View Related
Oct 30, 2006
I want to pull out some information for documenting my user accounts.I want to be able to show all of the users and what companies those users have access to.
The table which stores the company information lists it in multiple rows, so there will be many results for each user
user -- companyid
johnd -- 2
johnd -- 5
johnd -- 1
I want to select this into one record so it will show up like this
user -- companies
johnd -- 2,5,1
The only way I know how to do this would be with a sub-query that uses a cursor to loop through & dump it into one string value, and then output the string value to the field. This seems extremely inefficient for such a seemingly simple task.
Can somebody help me out here?
thanks
View 3 Replies
View Related
Oct 17, 2012
I need to normalise comma separated strings of tags (SQL Server 2008 R2).
E.g. (1, 'abc, DEF, xyzrpt') should become
(1, 'abc')
(1, 'DEF')
(1, 'xyzrpt')
I have written a procedure in T-SQL that can handle this. But it is slow and it would be better if the solution was available as a view, even a slow view would be better.
Most solutions I found go the way round: from (1, 'abc'), (1, 'DEF') and (1, 'xyzrpt'), generate (1, 'abc, DEF, xyzrpt').
If memory serves, it used "FOR XML PATH". But it's been a while and I may be totally wrong.
View 2 Replies
View Related
Sep 15, 2006
I am a new user to SQL an I need to create a data base record from a comma delimted file (.CVS). The CVS file has up to ten fields all alpha/numeric. I must create this data base file using a stored procedure! The data base records will be displayed on a grid screen but this grid view will not be used to update the original CVS file.
View 6 Replies
View Related
Jan 18, 2006
I need some help with a stored procedure to insert multiple rows into a join table from a checkboxlist on a form. The database structure has 3 tables - Products, Files, and ProductFiles(join). From a asp.net formview users are able to upload files to the server. The formview has a products checkboxlist where the user selects all products a file they are uploading applies too. I parse the selected values of the checkboxlist into a comma delimited list that is then passed with other parameters to the stored proc. If only one value is selected in the checkboxlist then the spproc executed correctly. Also, if i run sql profiler i can confirm that the that asp.net is passing the correct information to the sproc:
exec proc_Add_Product_Files @FileName = N'This is just a test.doc', @FileDescription = N'test', @FileSize = 24064, @LanguageID = NULL, @DocumentCategoryID = 1, @ComplianceID = NULL, @SubmittedBy = N'Kevin McPhail', @SubmittedDate = 'Jan 18 2006 12:00:00:000AM', @ProductID = N'10,11,8'
Here is the stored proc it is based on an article posted in another newsgroup on handling lists in a stored proc. Obviously there was something in the article i did not understand correctly or the author left something out that most people probably already know (I am fairly new to stored procs)
CREATE PROCEDURE proc_Add_Product_Files_v2/*Declare variables for the stored procedure. ProductID is a varchar because it will receive a comma,delimited list of values from the webform and then insert a rowinto productfiles for each product that the file being uploaded pertains to. */@FileName varchar(150),@FileDescription varchar(150),@FileSize int,@LanguageID int,@DocumentCategoryID int,@ComplianceID int,@SubmittedBy varchar(50),@SubmittedDate datetime,@ProductID varchar(150)
ASBEGIN
DECLARE @FileID INT
SET NOCOUNT ON
/*Insert into the files table and retrieve the primary key of the new record using @@identity*/ INSERT INTO Files (FileName, FileDescription, FileSize, LanguageID, DocumentCategoryID, ComplianceID, SubmittedBy, SubmittedDate) Values (@FileName, @FileDescription, @FileSize, @LanguageID, @DocumentCategoryID, @ComplianceID, @SubmittedBy, @SubmittedDate)
Select @FileID=@@Identity
/*Uses dynamic sql to insert the comma delimited list of productids into the productfiles table.*/ DECLARE @ProductFilesInsert varchar(2000)
SET @ProductFilesInsert = 'INSERT INTO ProductFiles (FileID, ProductID) SELECT ' + CONVERT(varchar,@FileID) + ', Product1ID FROM Products WHERE Product1ID IN (' + @ProductID + ')' exec(@ProductFilesInsert) EndGO
View 4 Replies
View Related
Apr 27, 2015
I have one sp which has param name as cordinatorname varchar(max)
In where condition of my sp i passed as
coordinator=(coordinatorname in (select ltrim(rtrim(value)) from dbo.fnSPLIT(@coordinatorname,',')))
But now my promblm is for @coordinatorname i have values as 'coorcinator1', 'coordinato2,inc'
So when my ssrs report taking these values as multiselect, comma seperated coordinator2,inc also has comma already.
View 4 Replies
View Related
Nov 9, 2007
Using Flat File Connection Manager, I am specifying Text Qualifier = Double quotes{"}, and i have TXT file with one column for lastname and first name as "LN,FN", and settings are set to comma delimted, now the connectin manager is creating two different columns for LN and FN,
it was never a problem in DTS 2000.
any work around.
Thanks,
View 7 Replies
View Related
Aug 15, 2007
I created very simple table with 3 columns and one is varchar(max) datatype
When i insert records thru VC++ ADO code i am getting this error
Exception Description Multiple-step OLE DB operation generated errors. Check e
ach OLE DB status value, if available. No work was done. and Error Number:: -2147217887
ODBC Driver: SQL Native Client
SQL server 2005
Table
CREATE TABLE [dbo].[RAVI_TEMP](
[ID] [int] NULL,
[Name] [varchar](max) NULL,
[CITY] [varchar](50) NULL
)
VC++ code
#include "stdafx.h"
#include <string>
#include <strstream>
#include <iomanip>
int main(int argc, char* argv[])
{
try
{
HRESULT hr = CoInitialize(NULL);
_RecordsetPtr pExtRst = NULL;
_bstr_t bstrtDSN, bstrtSQL;
bstrtDSN = L"DSN=espinfo;UID=opsuser;PWD=opsuser;";
bstrtSQL = L"SELECT * FROM RAVI_TEMP";
_variant_t vartValueID,vartValueNAME,vartValueCITY;
_bstr_t bstrtValueID,bstrtValueNAME,bstrtValueCITY;
pExtRst.CreateInstance(__uuidof(Recordset));
hr = pExtRst->Open(bstrtSQL, bstrtDSN, adOpenDynamic, adLockOptimistic, adCmdText);
hr = pExtRst->AddNew();
bstrtValueID = L"1";
vartValueID = bstrtValueID.copy();
bstrtValueNAME = L"RAVIBABUBANDARU";
vartValueNAME = bstrtValueNAME.copy();
bstrtValueCITY = L"Santa Clara";
vartValueCITY = bstrtValueCITY.copy();
pExtRst->GetFields()->GetItem(L"ID")->Value = vartValueID;
pExtRst->GetFields()->GetItem(L"NAME")->Value = vartValueNAME;
pExtRst->GetFields()->GetItem(L"CITY")->Value = vartValueCITY;
pExtRst->Update();
pExtRst->Close();
}
catch(_com_error e)
{
printf("Exception Description %s and Error Number:: %d",(LPTSTR)e.Description(),e.Error());
return e.Error();
}
return 0;
CoUninitialize();
}
if i use regular SQL ODBC driver, no error but its truncating the data
Adv Thanks for your help
View 1 Replies
View Related
Apr 10, 2006
I have a file which contains comma separated columns. One of columns contains names of companies. Sometimes the names of the companies have a comma as part of the name. For those, the value is surrounded by double-quotes.
But it seems that SSIS ignores the double quotes and ONLY looks for the column separator. This causes my value to be split in half.
Traditionally, I thought parsers that deal with this type of import do not automatically take the first comma following the double-quote as the column separator but instead look for the first comma following the ending quote. (i.e. Look at how Excel performs imports...)
I cannot set the column separator of the column to double-quote comma since only those values that HAVE a comma in them are qualified.
Any ideas?
Here is sample fie content to see what I mean:
342123, Jason, 12345
21, Kim,4567
32.43, John Paul, 1245
23, "Mr. T", 98764
12, "Peter, Paul, Mary", 09643
The last entry should be imported as 12 in the first column, "Peter, Paul, Mary" in the second column and 09643 in the third but instead ends up as 12 in the first, "Peter in second column and Paul, Mary", 09643 in the last.
(Oddly enough, if I remove the first column of numbers the import works like it is supposed.)
View 3 Replies
View Related
Apr 19, 2007
Hi peso, hi KH, Hi everyone....
Declare @day int
set @day = 3
select right('0' + @day, 2)
My expected result is : 03
If single integer - will append in the right a '0'.
If 2 digit integer - will return the actual value.
Thanks.
-Ron-
"If you can only access one site on the Internet, make it SQLTeam!"
View 4 Replies
View Related
Jan 29, 2008
I am trying to return rows from a query and I want to display the information from 2 columns into one. Here is my query:
SELECT TOP (100) PERCENT dbo.CASES.CaseID, dbo.CASENUMBERTYPES.CaseNumTypeDesc, dbo.CASENUMBERS.CaseNumber,
dbo.SCANNEDDOCUMENTS.TopicID, dbo.EVENTS.EventTypeID, dbo.EVENTS.ev_StartDate, dbo.SCANNEDDOCUMENTS.Doc
FROM dbo.SCANNEDDOCUMENTS INNER JOIN
dbo.CASES ON dbo.SCANNEDDOCUMENTS.CaseID = dbo.CASES.CaseID INNER JOIN
dbo.CASENUMBERS ON dbo.CASES.CaseID = dbo.CASENUMBERS.CaseID INNER JOIN
dbo.CASENUMBERTYPES ON dbo.CASENUMBERS.CaseNumTypeID = dbo.CASENUMBERTYPES.CaseNumTypeID INNER JOIN
dbo.EVENTS ON dbo.CASES.CaseID = dbo.EVENTS.CaseID
WHERE (dbo.CASENUMBERTYPES.CaseNumTypeDesc IN ('cc', 'dc')) AND (dbo.EVENTS.EventTypeID IN (7048, 6467)) AND
(dbo.SCANNEDDOCUMENTS.TopicID IN (2, 3, 4)) AND (dbo.EVENTS.ev_StartDate > CONVERT(DATETIME, '2008-01-13 00:00:00', 102)) AND
(dbo.EVENTS.ev_StartDate < CONVERT(DATETIME, '2008-01-19 00:00:00', 102))
ORDER BY dbo.CASENUMBERTYPES.CaseNumTypeDesc, dbo.CASENUMBERS.CaseNumber
I get this for my return
1526959
CC
228762
2
7048
1/16/2008 12:00:00 AM
<Binary data>
CC is my CASENUMBERTYPES and the next column (228762) is CASENUMBERS
How can I get it to return it to where the CASENUMBERTYPES and CASENUMBERS show together in one column?
View 7 Replies
View Related
Jun 11, 2008
Hi there, I'm trying to concat the results of a select statement into a single row separated by commas without duplicates. The query and output is something like this:SELECT Specification FROM Cars WHERE Model = 112Which would return something like:Specification------------------Model 1Model 2Model 2Model 4 What I'd like is these to be combined into a single row such as:Specification
------------------Model 1, Model 2, Model 4
View 12 Replies
View Related
Jul 8, 2004
I want to use a NEWID() to generate order numbers, but i dont want to give customers the long uniqueID. so im wondering if i concatinate it to 8 characters, if that would be safe or not...
thx in adv
View 6 Replies
View Related
Feb 11, 2005
Hi,
I am trying to concat an int with an nvarchar in my select:
select distinct(id + name)
from load
where name not like '%test%'
but I am getting an error saying:
Server: Msg 245, Level 16, State 1, Line 1
Syntax error converting the nvarchar value '灪愭楮敭' to a column of data type int.
My question is: how do you concat int and string in MS SQL Server. The equivalent in Oracle would be ||, I think.
Thanks for any help.
Mongo
View 1 Replies
View Related
Feb 24, 2006
Hello,
I have a string let's say: "123".
I want to convert it to:
-- Start SqlServer
BEGIN
{CALL DBA.applsp_ChangeComments( 'ArtPurchPriceUpdate', 'TRIGGER', 'nl', 'ArtPurchPriceUpdate', '1' + CHAR(13)+ CHAR(10) +
'2' + CHAR(13) + CHAR(10) +
3' )}
END;
-- End SqlServer
-- Start Sybase
BEGIN
CALL DBA.applsp_ChangeComments( 'ArtPurchPriceUpdate', 'TRIGGER', 'nl', 'ArtPurchPriceUpdate', '1' + CHAR(13) + CHAR(10) +
'2' + CHAR(13) + CHAR(10) +
'3' );
END;
-- End Sybase
-- Start Oracle
BEGIN
ish.applsp_ChangeComments( 'ArtPurchPriceUpdate', 'TRIGGER', 'nl', 'ArtPurchPriceUpdate', '1' || CHR(13) || CHR(10) ||
'2' || CHR(13) || CHR(10) ||
'3' );
END;
/
-- End Oracle
This works well for oracle and sybase, for sqlserver I can't concatenate in a parameter of a stored procedure. I really want to do this. To create a variable is a lot of extra programming. Is there anyone who knows how to cancat these strings within the stored procedure call?
thanks beforehand,
Coen Dunnink
The Netherlands
View 7 Replies
View Related
Mar 2, 2006
how can i CONCAT 2 columns & () ?
SELECT CONCAT(A,B) AS C From myTAble
but I want to get A (B)
dog (red)
thank you
View 2 Replies
View Related
Dec 8, 2006
Hi,
i want to select 2 integer and a varchar fields as one. How can i do it?
Any ideas?
thanks
View 8 Replies
View Related
Jun 7, 2007
Hi everyone I'm trying to get 4 columns from my table to be on column, not sure how to go about it.
The column names are
X_POLICY_NO,
X_POLICY_EFCTV_DT,
PRODUCT_ABBR,
X_ASCO_CD
I would like to take those 4 columns in the select statement and make them on, I did in access but I tried
Select
(X_POLICY_NO, X_POLICY_EFCTV_DT, PRODUCT_ABBR, X_ASCO_CD) as CONCAT but i get an error that says :
Incorrect syntax, thanks for the help its greatly appreciated
View 5 Replies
View Related
Jul 2, 2007
I'm trying to get month/year from column X_POLICY_EFCTV_DT, i tried this
Concat(month(rr.X_POLICY_EFCTV_DT),
year(rr.X_POLICY_EFCTV_DT))
But i'm getting an error concat is not a recognized function name
is there a better way to get month/year from that column?
View 2 Replies
View Related
May 13, 2008
i have dataset like following:
ID name
============================
1 John
2 Dave
what i wan to do is show "John,Dave" in a single textbox, what should i do ? do i need a matrix table?
thx,
View 2 Replies
View Related
Jun 11, 2008
Hi there, I'm trying to concat the results of a select statement into a single row separated by commas without duplicates. The query and output is something like this:
SELECT Specification FROM Cars WHERE Model = 112
Which would return something like:
Specification
------------------
Model 1
Model 2
Model 2
Model 4
What I'd like is these to be combined into a single row such as:
Specification
------------------
Model 1, Model 2, Model 4
Kamran Shahid
Sr. Software Engineer(MCSD.Net)
www.netprosys.com
View 1 Replies
View Related
Aug 30, 2013
SELECT ROW_NUMBER() OVER (ORDER BY BM.BILL_NUMBER_V) AS [SL_NO],PP.KID_ID_NO_V AS [KID_NO],(PP.FIRSTNAME_V + SPACE(1) + PP.LASTNAME_V)AS [PATIENT_NAME],
CONVERT(VARCHAR(10),PP.UPDATEDDATE_D,101)AS [VISIT_DATE],BM.BILL_NUMBER_V AS [BILL_NUMBER],CONVERT(VARCHAR(10),BM.BILL_DATE_D,101) AS [BILL_DATE],
ROUND(BM.BILL_AMOUNT_M,2) AS [BILL_AMOUNT],ROUND(BM.CONCESSION_AMOUNT_M,2) AS [CONCESSION_AMOUNT],ROUND(BM.TOTAL_AMOUNT_M,2) AS [TOTAL_AMOUNT],
[Code] .....
In the above query i want to concat symbol '%' for output of percentage column. How to do that?
Eg: PERCENTAGE
30.00%
50.00%
View 1 Replies
View Related
Nov 6, 2007
will this work to create a whole date if YEAR_OPENED is a solid year. Like 1957 for example?
org_date_founded = YEAR_OPENED+'01-01'
View 3 Replies
View Related
Jun 26, 2007
If I have table1 and table2 with table2 having multiple rows tied to asingle row in table 1.What I am trying to do is set up a view that has one row that showsthe followingtable1.uniqueid, table1.name, table2.row1.detail, table2.row2.detail,table2.row3.detailI'd like to be able to do a select on the view and only come back withone row per widget. If possible, I'd actually like to be able toconcat all the rows from table 2 into one column if that's possible.table1.uniqueid, table1.name, (table2.row1.detail - table2.row2.detail- table2.row3.detail), table1.dateCreatedthxM@
View 1 Replies
View Related
Nov 23, 2007
Hello,I have a very simple problem which I will illustrate with an example:I have the following records in my table:A 1 CA 2 CA 3 CB 8 KB 9 KI now want to group them and the result has to be:A 1,2,3 CB 8,9 KSo the results in the second row have to be concatenated. I guessthere is no function to do this... What is the simplest solution?Kind regards,Bart Warnez
View 11 Replies
View Related
Jan 17, 2005
I want to concat strings such that if one string is null, it is treated as an empty string. For example 'abc' + NULL = 'abc'.
SQL Server has the CONCAT_NULL_YIELDS_NULL defaulted to ON, and it needs to be on in most cases when dealing with indices. (INSERT, DELETE, UPDATE, etc.) However, when I am running a select, and one field has a null value, I still want to see the other fields in the resulting string.
I can do this in a function, but I need a view, and the view doesn't seem to let me save a command with 'SET' in it. (However, it does let me run the command! And it works!) It's just when I try to save it, I get a syntax error, so the view is unavailable to me as I want it.
The command that works, but won't save is:
PHP Code:
SET CONCAT_NULL_YIELDS_NULL OFF
SELECT t1.field1+'-'+'t2.field2 AS viewField
FROM table1 t1 INNER JOIN
table2 t2 ON t1.fk1=t2.pk2
The tables look like this:
Table1
PHP Code:
create table user.dbo.table1
(
pk1 int primary key,
fk1 int,
field1 varchar(32),
FOREIGN KEY fk1 REFERENCES table2 (pk2)
)
Table2
PHP Code:
create table user.dbo.table2
(
pk2 int primary key,
field2 varchar(32)
)
table1
PHP Code:
pk1 fk1 field1
1 1 'test1'
2 2 'test2'
3 1 'test3'
table2
PHP Code:
pk2 field2
1 NULL
2 'tab2 test'
I expect to see:
PHP Code:
ViewField
test1-
test2-tab2 test
test3-
View 2 Replies
View Related
Nov 29, 2006
I cant find a clear answer to the syntax of concat in for SQL 2005. Can anyone help.
View 3 Replies
View Related
Apr 6, 2004
hello,
I'm wondering how it's possible to have a select statement resultant rows concatenated into one row and column.
For example:
select letter from alphabet_table
a
b
c
d
e
...
26 rows returned.
Other than a cursor, how would I write a query to return the following:
row1: abcdefghijkl...
thanks in advance!
View 5 Replies
View Related