473,386 Members | 1,741 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

Template function

Hi,

Suppose I have a table something like:

name (VARCHAR(64)) age (INT) quotation (TEXT)
=================================================
Donald Trump 50 I am rich
Bugs Bunny 26 What's up doc
...

and a template string something like:

SET @template = 'My name is {name}, my age is {age}, and I always say
"{quotation}".'

I'd like to be able to dynamically replace the placeholders in the
template string with values extracted from the corresponding columns in
the table, so I'd get a set of results like:

'My name is Donald Trump, my age is 50, and I always say "I am rich".'

The best I've come up with so far is:

SET @Query = 'SELECT '''
+ REPLACE(REPLACE(@String, '{', '''+CONVERT(varchar,'),
'}', ')+''')
+ ''' FROM Table'
EXEC (@Query)

This converts the template string into a query string, casting
everything to a
varchar to allow numeric values to work. In this case it would be:

SELECT 'My name is '+CONVERT(varchar,name)+', my age is '
+CONVERT(varchar,age)+', and I always say "'
+CONVERT(varchar,quotation)+'".'

The problem with this is that if the length of a varchar is
unspecified, it defaults to 30, which truncates long string values.

Can anyone figure out a way round this, or perhaps an alternative
method entirely?

--
Oli

Oct 10 '05 #1
5 2291
The fundamental principle of a tiered architecture is that you format
data for display in the front end and never in the database. Why do
you actively want to violate this?

Oct 10 '05 #2
(ca***@olifilth.co.uk) writes:
Suppose I have a table something like:

name (VARCHAR(64)) age (INT) quotation (TEXT)
=================================================
Donald Trump 50 I am rich
Bugs Bunny 26 What's up doc
...

and a template string something like:

SET @template = 'My name is {name}, my age is {age}, and I always say
"{quotation}".'

I'd like to be able to dynamically replace the placeholders in the
template string with values extracted from the corresponding columns in
the table, so I'd get a set of results like:

'My name is Donald Trump, my age is 50, and I always say "I am
rich".'

The best I've come up with so far is:

SET @Query = 'SELECT '''
+ REPLACE(REPLACE(@String, '{', '''+CONVERT(varchar,'),
'}', ')+''')
+ ''' FROM Table'
EXEC (@Query)

This converts the template string into a query string, casting
everything to a
varchar to allow numeric values to work. In this case it would be:

SELECT 'My name is '+CONVERT(varchar,name)+', my age is '
+CONVERT(varchar,age)+', and I always say "'
+CONVERT(varchar,quotation)+'".'

The problem with this is that if the length of a varchar is
unspecified, it defaults to 30, which truncates long string values.


SELECT replace(replace(replace(@template, '(name)', name),
'(age)', ltrim(str(age))),
'(quotation)', quotation)
FROM tbl
WHERE ...

I can't see any need for dynamic SQL. Or converting to varchar what is
already varchar. Or why you can't just say varchar(8000) instead of
just varchar if you must convert.

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

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techinf...2000/books.asp

Oct 10 '05 #3
--CELKO-- said the following on 10/10/2005 20:39:
The fundamental principle of a tiered architecture is that you format
data for display in the front end and never in the database. Why do
you actively want to violate this?


I agree that this is less than ideal.

The reason is that I want to auto-generate e-mails within a job (or
possibly a SP called from various jobs/triggers), based on the contents
of a particular table. So for lack of any real "front-end", this is
where I'm currently doing the processing.

--
Oli
Oct 11 '05 #4
Erland Sommarskog said the following on 10/10/2005 22:49:
(ca***@olifilth.co.uk) writes:
<...SNIP...>

The best I've come up with so far is:

SET @Query = 'SELECT '''
+ REPLACE(REPLACE(@String, '{', '''+CONVERT(varchar,'),
'}', ')+''')
+ ''' FROM Table'
EXEC (@Query)

This converts the template string into a query string, casting
everything to a
varchar to allow numeric values to work. In this case it would be:

SELECT 'My name is '+CONVERT(varchar,name)+', my age is '
+CONVERT(varchar,age)+', and I always say "'
+CONVERT(varchar,quotation)+'".'

The problem with this is that if the length of a varchar is
unspecified, it defaults to 30, which truncates long string values.

SELECT replace(replace(replace(@template, '(name)', name),
'(age)', ltrim(str(age))),
'(quotation)', quotation)
FROM tbl
WHERE ...

I can't see any need for dynamic SQL.


I don't like the idea of dynamically-generated code either ;), however...

The idea is that I want to automatically generate e-mails, based on the
contents of particular tables (the example above was just a trivial
example of the behaviour I want). The template strings need to be as
human-readable as possible, and could be updated on a regular basis
(they're likely to be stored in a table as well). Equally, new tables
could be added to the database in the future, and I want this procedure
to be as flexible as possible.

Therefore, I want to avoid hard-coding in any column names into the
job/proc.
Or converting to varchar what is
already varchar. Or why you can't just say varchar(8000) instead of
just varchar if you must convert.


I guess this is one possibility. However, is this likely to be inefficient?

I was hoping, perhaps erroneously, that there would be a way to obtain
any data type as a string-based type, formatted in the same way as when
one does:

SELECT name, age, quotation FROM table

When executed by SQL manager, query analyser, etc., the results are
shown as text, so something must have converted them from their native
data types!

--
Oli
Oct 11 '05 #5
Oli Filth (ca***@olifilth.co.uk) writes:
The idea is that I want to automatically generate e-mails, based on the
contents of particular tables (the example above was just a trivial
example of the behaviour I want). The template strings need to be as
human-readable as possible, and could be updated on a regular basis
(they're likely to be stored in a table as well). Equally, new tables
could be added to the database in the future, and I want this procedure
to be as flexible as possible.

Therefore, I want to avoid hard-coding in any column names into the
job/proc.
That is a mindset for which relational databases are not really built.

The idea is that the schema of a database - that is tables and columns -
are static. They may change if you install a new version of the application,
upon which you change your existing code. But tables and columns don't
come and go like a commuter train.

If the possible fields for the templates can vary over time, they
should be rows in a table, not colummns. You could have:

CREATE TABLE templates (tmplid int NOT NULL,
tmplname varchar(40) NOT NULL,
....
CONSTRAINT pk_templates PRIMARY KEY (templd))

CREATE TABLE templatefields
(tmplid int NOT NULL,
field varchar(12) NOT NULL,
datatype char(1) NOT NULL,
-- Permit integer, dates and varchar.
CONSTRAINT ckc_datatype CHECK (datatype IN ('I', 'D', 'V')),
CONSTRAINT pk_templatefields PRIMARY KEY (templid, field),
CONSTRAINT fk_templatefields FOREIGN KEY (tmplid)
REFERENCES templates (tmplid))

CREATE TABLE templatevalues
(tmplid int NOT NULL,
field varchar(12) NOT NULL,
valueno smallint NOT NULL,
value sql_variant NOT NULL,
CONSTRAINT pk_templatevalues
PRIMARY KEY (tmplid, field, valueno),
CONSTRAINT fk_templatevalues FOREIGN KEY (tmplid, field)
REFERENCES templatefields (tmplid, field))

Thus, the first table describes all templates. The second all fields in
a template, and the third all available values for a template.

To expand a template string you would have to loop over the fields
table and run a replace() for each possible field value in the template.

The point here is that users can add templates, fields and values as they
see fit, but the tables and columns are the same.
Or converting to varchar what is
already varchar. Or why you can't just say varchar(8000) instead of
just varchar if you must convert.


I guess this is one possibility. However, is this likely to be
inefficient?


Nothing of what you are doing right now is likely to be effecient.
And the cost of saying convert(varchar(8000) over convert(varchar(30)
is negligble.
I was hoping, perhaps erroneously, that there would be a way to obtain
any data type as a string-based type, formatted in the same way as when
one does:

SELECT name, age, quotation FROM table

When executed by SQL manager, query analyser, etc., the results are
shown as text, so something must have converted them from their native
data types!


Ohoh - you are not in Kansas anymore, you are down in the server. The
presentation you see in Query Analyzer and other tools is performed in
these tools. They get binary data from SQL Server. If you insist of doing
this in the server (a client is much more apt for this), you will have
use what is availble down there. And it's a bit primitive. (If you thought
this is messy, just wait until you have a field with a binary value!)
--
Erland Sommarskog, SQL Server MVP, es****@sommarskog.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techinf...2000/books.asp

Oct 11 '05 #6

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

Similar topics

5
by: Trevor Lango | last post by:
What is the appropriate syntax for placing a friend function that includes as one of it's parameters a pointer to the class object itself within the template class? I have the following: ...
5
by: Suzanne Vogel | last post by:
Is it possible to store a pointer to a template function? eg, template<class T> fooFunc() {...} fptr = fooFunc; // <-- I couldn't find any info here, not even in the forums:...
4
by: Thomi Richards | last post by:
Hi, I'm trying to create a simple stack class using C++ and templates. Everything works well and good if I amke the class totally inline. However, as soon as I try to seperate the class into a...
7
by: Lionel B | last post by:
Greetings. The following code compiles ok and does what I'd expect it to do: ---------- START CODE ---------- // test.cpp
9
by: Marek Vondrak | last post by:
Hello. I have written the following program and am curious why it prints "1" "2". What are the exact effects of explicitly providing function template parameters at the call? Is the second...
7
by: quarup | last post by:
I want to specialize a template function that lives inside a class, but am getting a compile error in VS.net 2003. Here's my code: template <class T> class A { public: template <class U> void...
12
by: stefan.bruckner | last post by:
Hi, I am looking for a way to achieve the following. I've tried a couple of things, but they all ended up being too complicated: I have a templated class A. I want another class B to be able...
5
by: StephQ | last post by:
This is from a thread that I posted on another forum some days ago. I didn't get any response, so I'm proposing it in this ng in hope of better luck :) The standard explanation is that pointer...
8
by: Jess | last post by:
Hi, I have a template function that triggered some compiler error. The abridged version of the class and function is: #include<memory> using namespace std; template <class T>
21
by: H9XLrv5oXVNvHiUI | last post by:
Hi, I have a question about injecting friend functions within template classes. My question is specific to gcc (version 3.4.5) used in combination with mingw because this code (or at least code...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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...
0
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...

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.