Transact SQL :: Concatenate String Using Conditions?
Sep 19, 2015
I have a SQL table like this
col1 Â Â Â col2 Â Â Â col3
1 Â Â Â Â Â 0 Â Â Â Â Â 0
1 Â Â Â Â Â 0 Â Â Â Â Â 1
1 Â Â Â Â Â 1 Â Â Â Â Â 1
0 Â Â Â Â Â 1 Â Â Â Â Â 0
I am expecting output asÂ
col1 Â Â Â col2 Â Â Â col3 Â Â Â NewCol
1 Â Â Â Â Â 0 Â Â Â Â Â 0 Â Â Â Â Â Â SL
1 Â Â Â Â Â 0 Â Â Â Â Â 1 Â Â Â Â Â Â SL,PL
1 Â Â Â Â Â 1 Â Â Â Â Â 1 Â Â Â Â Â Â SL,EL,PL
0 Â Â Â Â Â 1 Â Â Â Â Â 0 Â Â Â Â Â Â EL
condition if col>0 then SL else '', Â if col2>0 EL else '', if col3>0 PL else ''
View 5 Replies
ADVERTISEMENT
May 21, 2015
Have this table
ACCOUÂ NAMEÂ Â Â Â Â NAMEÂ TODATEÂ Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â IDÂ Â Â Â EDUCATÂ Â Â EXPIRYDATE
011647 MILUCON Empl1 1900-01-01 00:00:00.000 9751 VCA-basis 1900-01-01 00:00:00.000
011647 MILUCON Empl1 1900-01-01 00:00:00.000 9751 VCA-basis 2016-06-24 00:00:00.000
011647Â MILUCON Empl1 1900-01-01 00:00:00.000Â 9751Â VCA-VOLÂ 2018-02-11 00:00:00.000
Need to get it like
ACCOUÂ NAMEÂ Â Â Â Â NAMEÂ TODATEÂ Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â IDÂ Â Â Â EDUCATÂ Â Â EXPIRYDATEstring
011647 MILUCON Empl1 1900-01-01 00:00:00.000 9751 VCA-basis 1900-01-01 00:00:00.000 2016-06-24 00:00:00.000
011647Â MILUCON Empl1 1900-01-01 00:00:00.000Â 9751Â VCA-VOLÂ 2018-02-11 00:00:00.000
In other words I need to Aggregate the 2 dates and concatenated into a new string col string so basically a sum with a group by but instead of a sum I need to concatenate the string. I know this should be possible using stuff and for xml path but I can't seem to get my head around it everything I try concatenates all the strings, not just the appropriate ones.
View 11 Replies
View Related
May 13, 2015
I have the below problem:
DECLARE @t TABLE
(
ID int,Â
Name nvarchar(255)
)
INSERT INTO @t
SELECT 1, 'Raven'
[Code] ....
Returns the below:
ID Â Â Name
1 Â Â Â Â Raven
4 Â Â Â Â Raven
43 Â Â Â Jack
Any names which are appearing twice I would like to have only one row so concatenate the IDs into one row for each Name, like below:
ID Â Â Â Â Â Name
1, 4 Â Â Â Raven
43 Â Â Â Â Jack
Is this possible?
View 4 Replies
View Related
Oct 25, 2004
Please help me with this if you can.
I have one table with CustomerID and some other data.
In other table i have CustomerID(the link with the first table) and Agent
The relation of the first with the second one is ONE TO MANY.
I want something like this:
Customer,'Agent1,Agent2,Agent3'
Is it possible.
Please help :)
View 3 Replies
View Related
Mar 5, 2007
I hope this is the correct place to ask this...
I would like to concatenate a String value to an Int value using an SQL statement. At the moment it reads like this:
SELECT 'website.com/shop/product.cfm?ProductID=' + Products.ProductID AS Product_URL
But unfortunately I am getting the error:
"Conversion failed when converting the varchar value 'website.com/shop/product.cfm?ProductID=' to data type int."
Any idea how to get around this at all just using an SQL query statement?
View 2 Replies
View Related
Feb 20, 2008
Hi all I need some help in concatenatng a string in T-SQL. Having used the Command Microsoft Access inside the 'SQL View' window and typed the following it worked perfectly.
Code Snippet
UPDATE tblValidUsers SET blocked_users = blocked_users + 'name_123@hotmail.com;' WHERE userid='Onam'
However attempting the same command in T-SQL I get the following error:
Msg 403, Level 16, State 1, Line 1Invalid operator for data type. Operator equals add, type equals text.
Reason for having this command is I want to be able to add something to the end of the field "blocked_users" without actually overwriting the fields contents.
So for instance if I had the items: "Item1, Item2, Item3" in blocked_users and I updated it with "Item4" then the value "Item4" would be added to the end thus the use of "+" is used to concatenate. Is there a way of doing this in T-SQL?
Thanks for the help, Onam
View 6 Replies
View Related
Nov 6, 2010
Let’s say in one field there is the "year" as an integer 2010, and in another field is the "month" as an integer 11. How can you concatenate them and not add them?
Essentially the result I'm looking for based on the example would be this: 201011 but I still want this to be an integer and not a string.
View 16 Replies
View Related
Apr 22, 2008
Hi,
As I build a record set in an SP I need to add in a string containing a list derived from a second query. I need the results of the sub query to be presented as a single string in the first query, separated by a single space.
I have no idea how to do this in t-sql, and am doing it on the web server at the moment, but becase the dataset is quite large, I'm getting 20 - 40 second processing times which is far too long.
I have found reference to the xp_sprintf function but this is not supported by my host, so not a solution.
I'm no expert in t-sql, so I imagine there's a way somewhere, and would be grateful for any advice available.
regards,
NEIL
Neil
View 5 Replies
View Related
Sep 4, 2014
To start, I am NOT a SQL programmer. I have to do some minimal SQL administration (DB Creation, Backups, Security) on spatial databases that are for the most part managed by a 3rd party program. My experience with T-SQL is mostly simple tasks (i.e. Select and Update statements)..However I have been requested to calculate an ID Field using the values of two other fields. Per the request, I need to convert one field to Hex and concatenate with the second field.
ex. Field 1 + Field 2(hex string) = Field 3
Field 1 = 'FF02324323'
Field 2 = 'Smith Creek'
Field 3 = 'FF02324323536D69746820437265656B'
Field 1 VarChar(10) (Code)
Field 2 VarChar(65) (Common Name)
Field 3 VarChar(max) (ResourceID)
Spent half the day searching and have tried various forms of CAST, CONVERT, fn_varbintohexstr and others but have unable to come up with the correct combination to get what I need.
View 3 Replies
View Related
Oct 18, 2006
Hi to all:
In my package, I have in OLE DB SOURCE a statement:
DECLARE @CMonth as smalldatetime
SET @CMonth = '11/1/2006'
select day(@CMonth)+month(@CMonth)+year(@CMonth) as ID_Month
and in OLE DB DESTINATION, I have ID_Month column as a char(10).
I want to be result as concatenated string €“ 1112006, but I receive 2018 (As a result of calculation)
Can anybody help me? Thank you
View 3 Replies
View Related
Dec 2, 2015
I am trying to do a simple update in one sql table from another where a certain condition in both tables are met.I am missing something basic and have tried numerous posted examples, without success.Here is my code (that does not update) :
      opdragaliasnaaminsit.Connection = konneksie
       opdragaliasnaaminsit.CommandText = "UPDATE vyfjaarontledings " & _
       "SET aliasnaam = T2.aliasnaam" & _
       " FROM vyfjaarontledings T1" & _
       " INNER " & _
       "JOIN blokke T2 " & _
       " ON T1.plaasno = T2.plaasno " & _
        "WHERE T1.plaasno = T2.plaasno"
opdragaliasnaaminsit.ExecuteNonQuery()
I am trying to update aliasnaam in vyfjaarontledings from blokke.
View 10 Replies
View Related
Apr 23, 2015
SQL Version:Â 2008 (not r2)
Problem: My Select statement seems to be unaffected by some of the conditions in the WHERE Clause. For instance
JCCD.Mth >= cutoffs.FiscalYear_FirstMonth (value '20130101')Â AND JCCD.Mth <= @WIPMonthCurrent (value '20130101')AND LTRIM(RTRIM(JCCD.Job)) = '71-' (see output and code below)
SQL Code:
declare @WIPMonthCurrent date = '20130101'
SELECTÂ Â
    JCCD.JCCo, JCCD.Job, JCCD.Mth, JCCD.Source, sum(JCCD.ActualCost) AS CostToDate
[code]....
View 5 Replies
View Related
Oct 29, 2015
I need to concatenate the DisplayName column with distinct UserName and SysName using XML path
 SELECT [sysName], [User_Name],[DisplayName] FROM
 (SELECT v_Add_Remove_Programs.DisplayName0 AS [DisplayName], v_Add_Remove_Programs.Publisher0 AS [Publisher]
, v_R_System_Valid.Netbios_Name0 AS[sysName],v_R_System_Valid.User_Name0 AS [User_Name],v_Add_Remove_Programs.Version0 as [Version]
FROM [Offline].[dbo].v_Add_Remove_Programs
JOINÂ [Offline].[dbo].v_R_System_Valid ON [Offline].[dbo].v_Add_Remove_Programs.ResourceID = [Offline].[dbo].v_R_System_Valid.ResourceID)
[code]....
View 3 Replies
View Related
Oct 7, 2015
 I have a requirement .Where i might have multiple rows one of the row will have description and second row might be related description but wiht routning number null .I want to concatenate these rows
Id
Routingnum
Ddesc
1
101
A
[code]....
View 8 Replies
View Related
Dec 5, 2015
I have a table where I need to concatenate all values into one field separated by a comma. Â If the field is null display a blank value. Â This is my table structure and example output
Create Table #read
(
id int
,field1 varchar(100)
,field2 varchar(100)
,field3 varchar(100)
,field4 varchar(100)
[code]...
View 5 Replies
View Related
Feb 16, 2006
I've been trying to return hex data in a way that can be concatenated.
I need the actual hex info (e.g. 0x6E3C070) as displayed
since it contains info about the path to a file.
So I can turn it into D:6E3C 7 to get the path to the file.
In searching around I have come across a way to do this but can't figure out how to get it to run through a column and either display or insert into a table multiple results.
-Here's the user function that converts an integer into a hex string-
CREATE FUNCTION udf_hex_string (@i int)
RETURNS varchar(30) AS
BEGIN
DECLARE @vb varbinary(8)
SET @vb = CONVERT(varbinary(8),@i)
DECLARE @hx varchar(30)
EXEC master..xp_varbintohexstr @vb, @hx OUT
RETURN @hx
END
GO
-Using this table-
create table
XPages
(PageStoreId int null,
HexString varchar (30) null,
VolumePath varchar (60) null, )
--'PageStoreId' contains the data that needs to be converted into the editable hex string
--'HexString' is where I'd like it to go so I can parse it later.
--I can run the below select and get the hex string. But am stuck on how to run a select or update that would run through the 'XPages.PagestoreId'
column and insert the hex string into the 'XPages.Hexstring' column. 'XPages.PagestoreId' could have 100's of entries that need to be converted and placed in the relevant the 'XPages.Hexstring' column.
SELECT dbo.udf_hex_string(1234)
Thanks
View 3 Replies
View Related
Jul 23, 2005
The following query works perfectly (returning all words on a list called"Dolch" that do not contain a form of "doing"):SELECT 'Dolch' AS[List Name], dbo.Dolch.vchWordFROM dbo.Dolch LEFT OUTER JOINdbo.CombinedLexicons ON CONTAINS(dbo.Dolch.vchWord,'FORMSOF(INFLECTIONAL, "doing")')WHERE (dbo.CombinedLexicons.vchWord IS NULL)However, what I really want to do requires me to piece two strings together,resulting in a word like "doing". Any time I try to concatinate strings toget this parameter, I get an error.For example:SELECT 'Dolch' AS[List Name], dbo.Dolch.vchWordFROM dbo.Dolch LEFT OUTER JOINdbo.CombinedLexicons ON CONTAINS(dbo.Dolch.vchWord,'FORMSOF(INFLECTIONAL, "do' + 'ing")')WHERE (dbo.CombinedLexicons.vchWord IS NULL)I have also tried using & (as in "do' & 'ing") and various forms of singleand double quotes. Does anyone know a combination that will work?FYI, in case this query looks goofy because of the unused "CombinedLexicons"table, it is because the end result should be a working form of thefollowing...Figuring out the string concatination is just a step toward this goal:SELECT 'Dolch' AS[List Name], dbo.Dolch.vchWordFROM dbo.Dolch LEFT OUTER JOINdbo.CombinedLexicons ON CONTAINS(dbo.Dolch.vchWord,'FORMSOF(INFLECTIONAL, ' + dbo.CombinedLexicons.vchWord + ')')WHERE (dbo.CombinedLexicons.vchWord IS NULL)Thanks!
View 2 Replies
View Related
Jan 23, 2008
I've been trying to do the following:
Code Snippet
if year(@SomeDateTime) <> @SomeYear
set @SomeDateTime= convert(datetime, @SomeYear+ '1231', 112)
If variable @SomeDateTime evaluates to 20080101 and @SomeYear = 2006, I wish that my variable @SomeDateTime becomes 20061231 (December 31st).
The way it's written now, it doesn't work... @SomeDateTIme evaluates to 1908-11-12.... ?!
View 6 Replies
View Related
Jun 18, 2015
I have conducted a thorough search in the forums and cannot quite find my answer. I have a date field called open_date. If the open_date is more than 30 days old, I need to count it. I have started with the following code:
SELECT 'Older_Than_30Days' =
CASE
WHEN open.date >= 30 THEN '1'
ELSE '0"
END
My problem is the WHEN.
View 6 Replies
View Related
Jun 1, 2015
I have following query. Now I want to change this in such a way that if Condition 1 satisfies then it should not go to next condition ,if not then should go to next. Similarly the same format till condition 4.
select * from table where
IND = 'Y'
and
(
(STATE = @STATE and LOB =@LOB and COMPANY=@COMPANY)--Condition 1
OR
(STATE = @STATE and LOB =@LOB)--Condition 2
OR
(STATE = @STATE and COMPANY=@COMPANY)--Condition 3
OR
(STATE = @STATE)--Condition 4
)
View 4 Replies
View Related
Oct 20, 2015
I need to update many rows in some table. Â I've made such SQL query:
UPDATE [%TableName%]
SET [%FieldName%] = CASE
           WHEN ID = 1 THEN '1'
           WHEN ID =2 THEN '2'
           ....
      END;
      [%FieldName2%] = CASE
           WHEN ID = 1 THEN '1'
           WHEN ID = 2 THEN '2'
           ....
      END;
WHERE ID IN {1, 2, ...}
Are there some limitations for CASE operator? How many "when - then" conditions can I include in query?
View 6 Replies
View Related
Mar 27, 2007
I have a large table that looks like this.
(ID INT NOT NULL IDENTITY(1,1),PK INT , pocket VARCHAR(10))
1, 1, p12, 1, p23, 2, p34, 2, p45, 3, p56, 3, p67, 4, p78, 5, p19, 5, p210,5, p83
i would like to loop through the table and concatenate the pocket filed for all the records that has the same pk. and insert the pk and the concatenated string into another table in a timely manner.
can anyone help?
i have to use temporary tables. (not cursors-with cursors i know how to di it, but i want with temporary table)
thanks in advance
View 1 Replies
View Related
May 11, 2006
I need help.
I have a large table that looks like this.
(ID INT NOT NULL IDENTITY(1,1),PK INT , pocket VARCHAR(10))
1, 1, p1
2, 1, p2
3, 2, p3
4, 2, p4
5, 3, p5
6, 3, p6
7, 4, p7
8, 5, p1
9, 5, p2
10,5, p83
i would like to loop through the table and concatenate the pocket filed for all the records that has the same pk. and insert the pk and the concatenated string into another table in a timely manner.
can anyone help?
Emad
View 9 Replies
View Related
Sep 15, 2005
I've created a search page in my asp.net app that allows the user to enter optional parameters to narrow down the result set. It looks something like:Find all parts where: manuafacturer: <dropdownlist>ANY | manufacturer 1 |... </dropdownlist> model: <dropdownlist>ANY | model 1 |... </dropdownlist> cost: between <textbox> and <textbox> dollarsCurrently I create the SQL command on the fly building the WHERE based on what the user selects. For example if in the form above they select manufacturer = manufacturer1 model = ANY cost = between 10 and 15the WHERE string is ... WHERE manufacturer='manufacturer1' AND cost BETWEEN 10 AND 15Since the user doesn't care about model I leave it out of the WHERE. OK so here is my question. I want to move my queries to strored procedures however I'm not sure how to create the query since it changes based on what the user enters. Using the example above I'm assuming I can create one query with 4 parameters however what value would I use for ANY? parameter1 (manufacturer) = "manufacturer1" parameter2 (model) = ??? parameter3 (price low) = 10 parameter4 (proce high) = 15I see there is an ANY operator in T-SQL but it doesn't look like the right thing to use. Should I use LIKE '%'? Seems that using LIKE would result in addition overhead.ThanksSimon
View 2 Replies
View Related
Sep 16, 2015
I have a datetime field for e.g 2015-09-15 00:00:00.000 and an integer field for e.g.100809.
The integer field is actually a time value as in hours,minutes,seconds. For e.g. the value
100809Â means
10-hours
08-minutes
09-seconds
I need to combine the datetime and the int field to get the output as below
2015-09-15 10:08:09
View 7 Replies
View Related
Jan 10, 2012
I am working with a SQL Server database that was set up to store the year, month, and day in separate columns, rather than use a single column for the date. I plan to change this so that we store dates and times using the datetime data type. Until then, for now, I need to write transact-SQL select statements to concatenate the year, month and day to create a date that can be displayed in the results window in the format yyyy/mm/dd.
I can't seem to find any built-in function in SQL Server that will let me do this. Of course, using Excel or Access, I can use the DATE() function to reconstruct the date into yyyy/mm/dd. Is there a way to reconstruct the date into yyyy/mm/dd in SQL Server?Â
View 7 Replies
View Related
May 26, 2008
Hi,
I need to concatenate a string with an int variable on a stored procedure; however, i looks like i am lost in single and double quotes. Does any one know the right comination of quotes for this please? My Code is below:
1 @Price int
2
3 DECLARE @SqlPrice varchar(50)
4
5 if (@Price is not null)
6
7 set @sqlPrice = 'AND price' + '' > '' + '' + @Price + ''
8
View 4 Replies
View Related
Oct 13, 2015
The data I have is as follows -
ID1   ID2    Date           Action
100Â Â 500Â Â Â Â 09/08/14Â Â Â Â Open
100Â Â 500Â Â Â Â 09/24/14Â Â Â Â Close
101Â Â 510Â Â Â Â 07/10/15Â Â Â Â Open
101Â Â 510Â Â Â Â 07/19/15Â Â Â Â Close
The output I want in a single result set is -
ID1   ID2    Open_Date  Close_Date
100Â Â Â 500Â Â Â 09/08/14Â Â Â Â Â 09/24/14
101Â Â Â 510Â Â Â 07/10/15Â Â Â Â Â 07/19/15
Any way to do this in T-SQL .
View 10 Replies
View Related
Jan 10, 2008
My question is fairly simple. When I join between two tables, I always use the ON syntax. For example:
SELECT
*
FROM
Users
JOIN UserRoles
ON (Users.UserRoleId = UserRoles.UserRoleId)
No problems there. However, if I then decide to further filter the selection based on some trait of the UserRole, I have two options: I can add the condition as a WHERE statement, or I can add the condition within the ON block.
--Version 1:
SELECT
*
FROM
Users
JOIN UserRoles
ON (Users.UserRoleId = UserRoles.UserRoleId)
WHERE
UserRoles.Active = 'TRUE'
-- Version 2
SELECT
*
FROM
Users
JOIN UserRoles
ON (Users.UserRoleId = UserRoles.UserRoleId
AND UserRoles.Active = 'TRUE')
So, the question is, which is faster/better, if either? The Query Analyzer shows the two queries have the exact same execution plan, which makes sense, since they're both joining the same tables. However, I'm wondering if adding the condition in the ON statement results in fewer rows the JOIN statement initially needs to join up, thus reducing the overall initial size of the results table before the WHERE conditions are applied.
So is there a difference, performance wise? I imagine that if Users had a thousand records, and UserRoles had 10 records, then the JOIN would create a cartesian product of the two tables, resulting in 10,000 records in the table before the WHERE conditions are applied. However, if only three of the UserRoles is set to Active, would that mean that the resulting table, before applying WHERE conditions, would only contain 3000 records?
Thanks for whatever information you can provide.
View 7 Replies
View Related
Sep 1, 2015
Is there way to search for the particular string and return the string after that searched string
SalesID
Rejection reason
21812
[code]....
The timeout period elapsed hence disqualified
View 3 Replies
View Related
Jul 28, 2015
I have a string variable and following data.
Declare @ServiceID varchar(200)
set @ServiceID='change chock','change starter','wiring for lights','servicing'
when I assign values in @ServiceID Â in the above manner then it shows error. How to get string array in @ServiceID variable so that i can go ahead.
View 8 Replies
View Related
Sep 9, 2015
I want to split the string 'MR JAMES WELL II' into three what is the easiest way of doing?
First part = MR
Second part = II
Third part = JAMES WELL
Tried couple of methods using CHARINDEX/REVERSE but not getting through.
View 8 Replies
View Related
May 18, 2015
DECLARE @FullName     VARCHAR(100)
SET @FullName = 'Vauxhall Adam Rocks AIR Vauxhall'
SELECT LEFT(@FullName, NULLIF(CHARINDEX(' ', @FullName) Â -1, -1)) AS [FirstName],
    RIGHT(@FullName, ISNULL(NULLIF(CHARINDEX(' ', REVERSE(@FullName)) - 1, -1), LEN(@FullName))) AS [LastName]
This is only gives first and last not first and middleÂ
Â
DECLARE @FullName     VARCHAR(100)
SET @FullName = 'Vauxhall Adam Rocks AIR Vauxhall'
SELECTÂ
STUFF(@FullName,charindex(' ',SUBSTRING(@FullName,5,LEN(@FullName)))+5,LEN(@FullName),'') [Firstname1],
 STUFF(@FullName,1,charindex(' ',SUBSTRING(@FullName,5,LEN(@FullName)))+4,'') Lastname1
Not right as it givesÂ
VauxhallÂ
Adam Rocks AIR Vauxhall
Ideally the result should beÂ
Vauxhall
Adam Rocks AIRÂ
View 6 Replies
View Related