String Concatenation
Feb 21, 2006I'm trying to concatenate 3 columns into 1. Can someone provide me w/ the syntax?? :) thx
View 1 RepliesI'm trying to concatenate 3 columns into 1. Can someone provide me w/ the syntax?? :) thx
View 1 RepliesHi,
Why does this result produce 'Null' and not the expected string of 10 B's?
The var @SecurityString is a VarChar Type.
WHILE @LoopCount <= 10
BEGIN
SET @SecurityString = @SecurityString + 'B'
SET @LoopCount = @LoopCount + 1
END
SELECT @SecurityString AS SecurityCode
Any pointers would be a great help, thanks.
create procedure ChangePassword(@sUser char(20),@sPassword char(20))
as
begin
execute immediate 'GRANT CONNECT TO ' + @sUser + ' IDENTIFIED BY ' + @sPassword
grant execute on ChangePassword to public
end
I m getting syntax error at '+' sign. I saw in BOL and it is exactly the same.
Can nyone help me out?
Thx
create procedure CheckSQLErrors( @TheCode integer, @TheState integer, @Routine varchar(40), @Help varchar(40))
as
begin
{ call LogMsg('SQLA',@Routine,@Help,'sqlstate=' + @TheState +
', sqlcode=' + @TheCode) }
end
I m getting this error.
"Incorrect syntax near + "
+ is used for string concatenation. I tried to use CAST to convert
@TheState and @TheCode variables to varchar but did not work. Can you help me out?
FYI
LogMsg is a sproc
create procedure
dbo.LogMsg( @aAppName varchar(18), @aRoutine varchar(20), @aType varchar(5), @aMsg varchar(255))
as
begin
insert into MessageLog(strAppName,strRoutineName,strType,strMe ssage) values(
@aAppName,@aRoutine,@aType,@aMsg)
end
GO
Thks
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..
I want to concatanate all text rows returned by the following sql statement:
"SELECT Text FROM PageText WHERE PageTextId = 1"
Table "PageText" has the following columns:
---------------------------------------------
PageTextId (int)
SortOrder (int)
Text (nvarchar(4000))
Is it possible to do this? Kinda like doing a "SUM()" if the values would have been numeric?
Hi all,
I have a sitaution here where I need to convert some relational data to a flat file. I have a primary record that flatens out pretty well with the exception of two columns that need to have row data converted to strings via concatenation. The column size is Char(146) . I attempted to use 2 cursors to create the strings.
C1 --outside cursor to pull unique record id (161,000+ records)
C2 -- SELECTs the top 29 secondary (relational) records for each C1 rec
(FIELDX as Char(5))
FIELDX is the concatenated up to 29 times and inserted in to a flat table
based on record id for flat file export.
The issue is that this takes FOREVER to run and the 3Ghz XEON w/2GB Ram server weeps.
Declarations are as follows:
DECLARE C1 CURSOR FAST_FORWARD READ_ONLY
FOR
SELECT Distinct Record_ID
FROM tblProcedure
DECLARE C2 CURSOR FAST_FORWARD READ_ONLY
FOR
--need only the top 29 relational records to string out
SELECT TOP 29 Cast(pr_icd1 as Char(5))
FROM tblProcedure WHERE Record_ID = @RECID --From C1
OPEN C2
SET @tmpICDstr = ''
FETCH NEXT FROM C2 INTO @tmpICDchar
WHILE @@FETCH_STATUS = 0
BEGIN
SET @tmpICDstr = @tmpICDchar + @tmpICDstr
FETCH NEXT FROM C2 INTO @tmpICDchar
END
--'INSERT INTO [Validation].[dbo].[tmpICDStr] (RECID, sg) VALUES
(@RECID, @tmpICDstr)
--'INSERT INTO @tmp (RECID, STRsg) VALUES (@RECID, @tmpICDstr)
SET @tmpICDchar = ''
Anybody have a suggestion on how to speed this up. I am looking at about 1min/100 C1 records. Do the math for 161,000+ C1 records. Ugh.
Any suggestion would be appeciated!
tnx
Hi,How can I remove a part of string from complete string in SQL?this is something i want to do:update aceset PICTURE = PICTURE - '\SHWETABHShwetabhI'But here ' - ' is not allowed.How can I remove the string \SHWETABHShwetabhI from the columnPICTURE?Regards,Shwetabh
View 5 Replies View RelatedDear GroupJust wondered how I can avoid the CHAR(32) to be inserted if @String1 is NULL?SET @String3 = ISNULL(@String1,'') + CHAR(32) + ISNULL(@String2,'')Thanks very much for your expertise and efforts!Best Regards,Martin
View 6 Replies View RelatedI guess I'm the only one with this problem -- couldn't find anything on it in the back questions. Maybe it's a weird problem. :)
Anyway, although I'm not new to SQL, I am a bit new to stored procedures, and MS SQL Server 7. (I've been using mySQL, decent, but doesn't have many features ... )
I used some ASP and stored procedure code from 4guysfromrolla.com for session tracking through SQL Server.
I've modified most of the stored procedures so that they actually work. :)
The tables it uses are simple:
sessions: sessionid (uniqueidentifier), date_stamp (datetime), sessionipaddr(varchar(50))
sessionvalues: sessionid (uniqueidentifier), sessionvalname (varchar(100)), sessionvaldata (varchar(8000))
To answer some questions before they're asked: It's a resume database, and does need to be able to store 8000 characters at a shot. (I'm hoping 8000 is as large as it gets for this particular field.)
There's only one problem now: One of the stored procedures enters information into the sessionvalue field of the table. However, much of our data contains apostrophes ('), and we need to be able to store them. I thought that modifying the execute statement would do it, something like:
EXECUTE sessiondata '{EC8131F6-409A-11D4-8E88-00A0C9E4F36E}', 'ExpWorkDescs', 'Here' + CHAR(39) + "s some data"
This doesn't work. Indeed, even if the concatenation worked, CHAR(39) doesn't in this context.
Then I thought I'd be really clever, and try a trick from mySQL:
EXECUTE sessiondata '{EC8131F6-409A-11D4-8E88-00A0C9E4F36E}', 'ExpWorkDescs', 'Here's some data'
Naturally, that one didn't work, either. (That was a long shot, admittedly!)
This is mission-critical. Not only apostrophes, but quotes and other punctuation marks must be able to be transferred. Anyone know a way to do it?
I have 8 fields - I have requirement to concatenate using '+' operator with semicolon delimiter but issues is in the
Output I get semicolons for the fields that are empty below is my code :
-------------
case
when [SLII Request Type] ='Job Posting' and [SmartLaborII Request Status] like 'Pending Approval (Level 4%'
and [New Extension or Replacement Audit Flag] like 'FLAG%'
then 'Reject – New, Extension, Replacement invalid entry' --'it is jp'
else ''
end as [ES Fully approved data 1],
case
[Code] ....
I have a need to create a table in a sql server database from C# code. The kicker is that the user must be able to specify the table and field names via the UI. I can do a bit of sanity checking but as long as they enter something reasonable I need to accept it. Normaly I always ADO parameters to sanitise any user parameters but they can't be applied to table and field names, only values. As far as I'm aware that leaves me needing to concatenate strings and that's something I usually avoid like the plague due to risk of SQL injection.
My actual question : Assuming string concatenation is my only way forward, how can I sanitise the values that would go into the table name and fieldname bits of a CREATE TABLE statement to ensure that injection can't occur? I've been pondering it and I think I just need to check for semi-colons. Without a semi-colon I don't think a user could inject an extra statement could they?
Hi,I'm trying to concatenate a Description (nchar(100)) and Date(datetime) as Description and my initial effort was just"...description+' '+open_date as description..." which throws a date/string conversion error; finally came up with a working string belowbut don't think it's the optimal way to do this - any suggestions?select (rtrim(description)+''+rtrim(convert(char(2),datepart(mm,open_date)))+'/'+convert(char(2),datepart(dd,open_date))+'/'+convert(char(4),datepart(yyyy,open_date))) as description fromoncd_opportunity where opportunity_id=?open_date is not a required field at the db level, but it is requiredon the form so it should not be null as a rule.
View 2 Replies View RelatedI 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!
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 RelatedI 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?
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-
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.
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,
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
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
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 RelatedHi,
I'm trying to mak emy query dynamic such that depending upon certain conditions, the conditions in the WHERE clause change. I have my SP as shown below and it doesn't seem to work correctly this way and seems like it is not even taking it as a condition. Please advise on what is going wrong here. I'm building the @Condition variable dynamically and appending it to the where clause below. Any help wud be greatly appreciated.
Thanks
CREATE PROCEDURE dbo.CabsSchedule_ViewSchedule
(
@SiteCode smallint = 0,
@YearMonth int = NULL,
@ByYearMonth bit = 1
)
AS
DECLARE @tempYearMonth int
DECLARE @Condition varchar(1000)
SET @tempYearMonth = 0
IF @YearMonth IS NULL OR @YearMonth = 0
BEGIN
EXECUTE CabsSchedule_GetYearMonth @tempYearMonth, @YearMonth OUTPUT
END
IF @ByYearMonth = 0
BEGIN
DECLARE @Year int
DECLARE @Month int
SET @Year = CAST(SUBSTRING(CAST(@YearMonth AS VARCHAR(6)),1,4) AS INT)
SET @Month = CAST(SUBSTRING(CAST(@YearMonth AS VARCHAR(6)),5,2) AS INT)
SET @Condition = ' DATEPART ([month], FullDate) = ' + CAST(@Month AS VARCHAR(2)) + ' AND DATEPART ([year], FullDate) = ' + CAST(@Year AS VARCHAR(4)) + ' AND '
END
ELSE
BEGIN
SET @Condition = ' YearMonth = ' + CAST(@YearMonth AS VARCHAR(6)) + ' AND '
END
SELECT BillPeriod =
CASE
WHEN BillPeriod = 32 THEN 'NB'
WHEN BillPeriod = 33 THEN 'Holiday'
ELSE Convert(nVarChar(7), BillPeriod)
END,
WorkDay =
CASE
WHEN WorkDay = -1 THEN ''
WHEN WorkDay = 0 THEN 'Holiday'
ELSE Convert(nVarchar(7), WorkDay)
END,
JulianDate, CalendarDay, CalDayBillRcvd, Remarks, FullDate
FROMdbo.CabsSchedule
WHERE YearMonth = @YearMonth AND SiteCode = @SiteCode
GO
I'm trying to implement a system where I want to use something like a group by with a concatenation clause.
e.g.
Table 1.
ID Field
1 null
2 null
Table 2.
ID Value
1 AAA
1 BBB
2 CCC
2 DDD
2 EEE
Using one query I would like to transform Table 1 to
ID Field
1 AAABBB
2 CCCDDDEEE
Is there any way of doing this ? At the moment I'm using two cursors to accomplish this task, but this is not really efficient.
Maurice v/d Zwaan
i am having data something like this:
number starting point ending point
1 ABC DEF
2 DEF ABC
1 PQR STU
2 STU PQR
1 ABC DEF
2 DEF PQR
3 PQR ABC
and i want it to be like this in my new table based on number column:
CONCATENATED
ABC/DEF/ABC
PQR/STU/PQR
ABC/DEF/PQR/ABC
can anyone suggest me how to write a query for this one?
Hi all,
I am trying to concatenate two columns First_Name and Last_Name to display as Name in a View. I used the following statement but the result only shows the First_Name.
Select First_Name + Last_Name as Name from Address;
How do i combine the two columns??
SQL 2000 running on Win 2000
Thanks in advance.
Hey,
Does anyone know how to do integer concatenation using sql?
Say for instance I have 2004 and 12, I need 200412 and not 2016.
Can this be done?
Thanks
I have an instance where I need to concatenate some data that is stored in a text datatype. I can't cast it to a varchar/char because that may well truncate the data. I just read about UPDATETEXT, which I think I can use, but I need to use it for a bunch or rows and it looks like this works on one row at a time. Anyone have experience with this?
View 7 Replies View RelatedI am using the following sql statement to concatenate fields from a sql server in my query.
SELECT RTRIM(title) + ' ' + RTRIM(fname) + ' ' + RTRIM(lname) AS name, id FROM contact
2 questions:
1. How can I avoid a Null name field resulting from either fname or lname being Null? One Null field in the contatenation yields a Null field, even though the other field is not Null.
2. Does concatentation in the sql statement reduce performance significanlty?
Hi all,
I am using concatenation in Query in Sql Server like,
Select Column1 + ' bla bla ' + Column2 as MyColumn from MyTable
So, here any secruity issure occur or not.... because some one tell to me.. d'not use Concetenation in query bcz it is not secure, worst in performance and helpfull in SQL injection.......
any idea about that ??
Thanks
Sajjad
Hi Consider a table with a decimal and a string varibale.
DecString
3fred
23bill
I need to concatenate them but with leading zeros such as
03Fred
23Bill
Ideas please ??
Gerry
Hi, i have this query that is perfect on SQL2005 but in SQL2000 it gives me the error: "Column 'D.RevenueCode' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause."
SELECT SUBSTRING(D.RevenueCode, 5, 2) + ' ' +
(SELECT A.sdp_des
FROM vw_UNI_se_girev A
WHERE A.sdp = SUBSTRING(D.RevenueCode, 5, 2)
AND Cast(A.Comp AS Integer) = D.CompanyCode) AS RevenueGrpItem,
SUM(nSign * isNull(ItemAmount, 0)) AS GrandTotal
FROM SIC_Invoice_Header AS H, vw_SIC_Invoice_Detail AS D
WHERE H.CompanyCode = 1
AND H.StockCategory = 'INV'
AND H.CompanyCode = D.CompanyCode
AND H.StockCategory = D.StockCategory
AND H.SaleType = D.SaleType
AND H.TransactionType = D.TransactionType
AND H.SerialNo = D.SerialNo
AND D.RevenueCode is not NULL
GROUP BY D.CompanyCode, SUBSTRING(D.RevenueCode, 5, 2)
ORDER BY SUBSTRING(D.RevenueCode, 5, 2)
It appears that when I remove the + and put a comma it works correctly but that's not what I want !
Any suggestions?
Thanks in advance
Laurent
Guys,
I have following table where I need to concatenate varchar column.
For example
IDCOMMENT
__________________
1JOHN SMITH
1 SURRENDER
1TO COPS
I want to be able to group by ID and concatenate COMMENT field to 'JOHN SMITH SURRENDER TO COPS' for ID 1
Is there any way to accomplish this?
Any suggestions and inputs would help
Thanks