473,657 Members | 2,530 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

AttribDescripti on as calculated field

Hi

in T-SQL,

(how) is it possible to concatenate 3 (varchar) fields into one; either
in a SQL query or through a calculated field (or using a view, if
anybody can explain to me how to use views), according to the following
rules:

{
first 30 chars of Trim(AttributeV al1)

if resulting string<30 chars append
", " & first 30 chars of Trim(AttributeV al2)

if resulting string<30 chars append
", " & first 30 chars of Trim(AttributeV al3)
}
=> define as new field StockItemDescri ption

ideally I would like SQL Server to do this processing rather than
building all these answer strings on the client side.

tia
Axel

Jul 23 '05 #1
5 3584
>> ideally I would like SQL Server to do this processing rather than building all these answer strings on the client side. <<

Only if you are a bad programmer who does not understand the basic
idea of a tiered architecture or what First Normal Form means. Display
is not done in the database, but in the front end. If the
concatenation is actually a single data elment then replace the
existing three columns with one.

Please post DDL, so that people do not have to guess what the keys,
constraints, Declarative Referential Integrity, data types, etc. in
your schema are. Sample data is also a good idea, along with clear
specifications. It is very hard to debug code when you do not let us
see it.

For example, if you had correct DDL, a CHECK() constraint would make
sure you never need to TRIM() in the DML. Fields are not anything
like columns and one of the many differences is that a clumn has such
constraints. If you use the right words, you will have the right
mental model for SQL programming.

Use this in your SELECT statement or VIEWs if you just want a kludge
and not to fix the problem.

SUBSTRING (attrib_1 + ', ' attrib_2 + ', ' attrib_3, 1, 30) AS
stock_item_desc rp

Jul 23 '05 #2
Axel (re***********@ hotmail.com) writes:
in T-SQL,

(how) is it possible to concatenate 3 (varchar) fields into one; either
in a SQL query or through a calculated field (or using a view, if
anybody can explain to me how to use views), according to the following
rules:

{
first 30 chars of Trim(AttributeV al1)

if resulting string<30 chars append
", " & first 30 chars of Trim(AttributeV al2)

if resulting string<30 chars append
", " & first 30 chars of Trim(AttributeV al3)
}
=> define as new field StockItemDescri ption


SELECT str30 = substring(rtrim (AttributeVal1) ), 1, 30)
CASE WHEN len(AttributeVa l1) < 30
THEN ', ' + substring(rtrim (AttributeVal2) ), 1, 30)
CASE WHEN len(AttributeVa l1) + 2
len(AttributeVa l2) < 30
THEN ', ' + substring(rtrim (AttributeVal3) ), 1, 30)
ELSE ''
END
END

--
Erland Sommarskog, SQL Server MVP, es****@sommarsk og.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techinf...2000/books.asp
Jul 23 '05 #3
Erland, thanks for the suggestion.

The one I came up with was
SELECT
left( left(P.ProductN ame,30)+#
'('+left(SI.Att ributeValue1,30 )+' '
+left(SI.Attrib uteValue2,30)+' '
+left(SI.Attrib uteValue3,30),6 0)
+')' AS ItemDesc
but this is still not flexible enough, I might have to do the
processing on the client side. I want it to dynamically decide to give
more room than 30 chars to the ProductName if the space is not used up
by the concatenated Attribute Values

consider this example:
ProductName='AP EX 1/4" Hex Insert Pozidrive Screwdriver Bits'
AttributeValue1 ='3 1" '
AttributeValue2 =' '
AttributeValue3 =' '

This is returned as ItemDesc='APEX 1/4" Hex Insert Pozidrive (3 1")'
and truncates valuable information from ProductName although the
resulting string is not even near the 60 character limit.

In pseudo code my algorithm will look like:
retrieve separate ProductName, Attrib1 - 3
concatenate Attributes (each clipped to 30 chars) => Count length of
resulting AttribString
count length of ProductName
if length(ProductN ame & AttribString) > 60 then
clip(AttribStri ng) to 30
if length(ProductN ame & AttribString) > 60 then
ProductName=lef t(ProductName,6 0-len(AttribStrin g))
endif
endif
This would probably be possible with T-SQL if I could put it into a
function but I would not like to attempt it as part of a SELECT
statement. The easiest is to leave this to the client and write a
simple VBScript function. The other advantage is that since the
presentation layer (website) has control on the way this string is
displayed it might as well get control on how many chars are displayed,
so this wraps it quite nicely.

regards
Axel

Jul 23 '05 #4
Many thanks Celco for your input.

In fact I will revert to do processing client side, as it is
1. a lot easier than trying to do it in T-SQL,
2. presentation layer gets more control (e.g. I can change the number
of max characters to 70 w/o touching the SQL Server)

just to wrap up the thread...

The reason for trying to do this in the Stored Procedure was my maybe
misguided longing for encapsulation, and also a desire to streamline
the information going over the internet connection.

I am now only working for 1.5 weeks on ASP (most of this was spent with
research, mainly on CSS) and have since given up the desire to look at
the code in a more object oriented fashion (which was what I tried
before ASP when working with C++, VB, Access). I am slowly getting used
to the terrible mish mash of HTML and script code that seems to
constitute ASP programming.

The code I supplied was of course only pseudo code as I did not want to
suggest a certain way of solving the problem, this is why I did not use
DDL. Currently my SP looks like this - let me mention it uses dynamic
SQL (Where string built on web page) and I am aware of the security
risks that it poses; also I already got stick for it on the NGs - the
incoming string is chopped and cleaned (quotes are doubled, commas and
semicolons are stripped) in order to avoid SQL injection. I do not
supply complete table definitions as they are not necessary for the
question.
only these:
tblProduct.Prod uctName nvarchar(250)
tblProduct.Attr ibuteValue1 nvarchar(250)
tblProduct.Attr ibuteValue2 nvarchar(250)
tblProduct.Attr ibuteValue3 nvarchar(250)
(Sizes defined by Customer, hopefully I will be able to review and
shrink them a bit - most shared hosts only allow for a db size of 100
MB)

CREATE PROCEDURE dbo.findProduct s
@mycount int output,
@whereString varchar (1000)
AS

SET NOCOUNT ON

--Set a Default value for the Wherestring which will return all records
if the Wherestring is blank
IF @whereString is Null
SELECT @whereString = 'AND tblProduct.Prod uctID is not null'

--Declare a variable to hold the concatenated SQL string
DECLARE @SQL varchar(2500)

-- AND (((UPPER([TblProduct].[ProductName] + [ProductGroupCod e] +
[AttributeValue1] +
-- [SearchWords] + [tblSupplier].[SupplierCode] + [SupplierDesc]))
Like '%screw%'))

SELECT @SQL = 'SELECT SI.CatalogueNo, SI.TypeNo, ' +
'left( left(P.ProductN ame,30)+'' (''+ left(SI.Attribu teValue1,30) +''
''+ left(SI.Attribu teValue2,30)+'' ''+
left(SI.Attribu teValue3,30),60 )+'')'' AS ItemDesc,' +
' SI.Price,P.Prod uctName, P.ChapterCode, P.ProductGroupC ode,
DisplayOrder' +
' FROM (tblProduct as P LEFT JOIN tblStockItem as SI ON P.ProductID =
SI.ProductID) ' +
' LEFT JOIN tblSupplier ON P.SupplierCode = tblSupplier.Sup plierCode' +
' WHERE 1=1 ' + @whereString +
' GROUP BY P.ProductID, SI.CatalogueNo, DisplayOrder,
SI.AttributeVal ue1, SI.AttributeVal ue2,SI.Attribut eValue3,' +
' SI.TypeNo, P.ProductName, P.ChapterCode, P.ProductGroupC ode,SI.Price'

execute (@SQL);
GO

regards
Axel

Jul 23 '05 #5
Axel (re***********@ hotmail.com) writes:
This is returned as ItemDesc='APEX 1/4" Hex Insert Pozidrive (3 1")'
and truncates valuable information from ProductName although the
resulting string is not even near the 60 character limit.

In pseudo code my algorithm will look like:
retrieve separate ProductName, Attrib1 - 3
concatenate Attributes (each clipped to 30 chars) => Count length of
resulting AttribString
count length of ProductName
if length(ProductN ame & AttribString) > 60 then
clip(AttribStri ng) to 30
if length(ProductN ame & AttribString) > 60 then
ProductName=lef t(ProductName,6 0-len(AttribStrin g))
endif
endif
This would probably be possible with T-SQL if I could put it into a
function but I would not like to attempt it as part of a SELECT
statement. The easiest is to leave this to the client and write a
simple VBScript function. The other advantage is that since the
presentation layer (website) has control on the way this string is
displayed it might as well get control on how many chars are displayed,
so this wraps it quite nicely.


Indeed putting it in a UDF could have performance implications.

The good news is that this is precisely what the CLR is good for in
SQL 2005. That is, in SQL 2005, you would write a scalar UDF in VB .Net
(or C#). This gives you the compiled performance of a 3GL language
as opposed the interpreted T-SQL. Also, in SQL2005, they have improved
performance on UDF calls, so even scalar UDFs in T-SQL are less
expensive in SQL 2005.
--
Erland Sommarskog, SQL Server MVP, es****@sommarsk og.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techinf...2000/books.asp
Jul 23 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
7031
by: Bill Clark | last post by:
I have about 20,000 records pulled from Excel that I need to update. What I need to do is run an update query that bascially says: If a field is null, update it with the previous record value of that same field. In some instances, it will have to go back a few records before it finds a value that is not null. Can this be done? Thanks Bill
1
2333
by: Norbert Lieckfeldt | last post by:
MS Access 2002 here. I am just trying to set up a simple database for a friend who's an optician. Basically, all clients with address details, date of last eyetest and a drop-down combo box to choose a number of months to the next eyetest (3,6,12,24). I then have a calculated field in the form which works out the date of the next appointment on the basis of the previous two sets of information . All that works . I am now trying to set...
2
5355
by: hhathome | last post by:
In my report I have a calculated DateDiff Field, I also have a calculated count field. I'm trying to get a total of the DateDiff field and dividing it by the count field and I'm having problems -- it seems the calculated field is not storing the data for reuse, maybe -- does anyone have any suggestions? Thanks
4
4704
by: Stewart Lane | last post by:
I have read the threads on here about adding a calculated column to a dataset to get the concatenation of first and last name fields into a single name field and then binding the calculated field to the control on a form. I am coming to VB.NET and ADO.NET and SQL Server from Visual Foxpro with its embedded SQL. I'm used to being to combine fields on the fly inside my sql statement. Is it true that this can not be done using the above...
2
3610
by: ey.markov | last post by:
Greetings, in A2K VBA, I set the following recordset: Set rsGPValue = dbs.OpenRecordset("SELECT *, DateSerial(Year(),Month()+4,0) FROM tblGPValue AS OurDate, dbOpenSnapshot) and then I try to use this calculated field: If rsGPValue.Fields("OurDate") > {Forms]!!.Value
3
4739
by: kelley.l.turner | last post by:
Hi all, I am very new to MS Access so please bear with me! I have created a simple calculated field in my data entry form, yet when I view my data table or try to generate a report based on this calculated field, no value is posted. How/where do I get my calculated values to also show up in the tables and reports? Thanks, Kelley
5
5885
by: Henrik | last post by:
The problem is (using MS Access 2003) I am unable to retrieve long strings (255 chars) from calculated fields through a recordset. The data takes the trip in three phases: 1. A custom public function returns a long string. This works. 2. A query has a calculated field based on the custom function above. This works when the query is run directly.
9
7807
by: Haas C | last post by:
Hi all! Is there anyway I can override a value in a calculated field on a form? For example: I have a form which displays the following fields based on a query: Premium Due field has the value of 12,527.75 in it. Brokerage Due field is the calculated field which multiplies a factor
2
4279
by: mkbrady | last post by:
I have a query that includes calculated fields that generate numeric results. I have wrapped conversion functions CLng() and CDdl() around the calculated fields to ensure the data types are correct. The query results are correct in MS Access 2007 but when I export to MS Excel 2007, some of the numeric fields are converted to text. I cannot find an explanation. I am using a Macro to export, and would prefer to avoid VBA for this...
0
8324
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8842
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8740
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8513
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
7352
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
4173
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4330
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
1970
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1733
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.