473,624 Members | 2,223 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Dynamic evaluation

/* goal: dynamic evaluation of table row
platform: sql 2000
*/

use northwind;

declare @tbl sysname
set @tbl = 'customers'

EXEC('select count(*) from ' +@tbl)

/*
Why the following dynamic evaluation would fail
IF EXEC('select count(*) from ' +@tbl) = 0
PRINT 'no rows'

Its variant,
IF exists (EXEC('select count(*) from ' +@tbl)) = 0
PRINT 'no rows'
*/

Do I know more sleep :)

TIA.

Jul 23 '05 #1
31 3670
> Why the following dynamic evaluation would fail
IF EXEC('select count(*) from ' +@tbl) = 0


Because EXEC is a statement, not an expression.

You could insert the result of EXEC into a table

INSERT INTO foo (table_name, row_count)
EXEC('select '''+@tbl+''',co unt(*) from ' +@tbl)

and retrieve the value from there.

Or you could use sp_executesql to pass input and output parameters.

Or you could retrieve the rowcount from SYSINDEXES (based on index stats so
there is some latency between the physical rowcount and the count updated in
SYSINDEXES).

--
David Portas
SQL Server MVP
--
Jul 23 '05 #2
On 17 Jan 2005 12:32:34 -0800, NickName wrote:
/* goal: dynamic evaluation of table row
platform: sql 2000
*/

use northwind;

declare @tbl sysname
set @tbl = 'customers'

EXEC('select count(*) from ' +@tbl)

/*
Why the following dynamic evaluation would fail
IF EXEC('select count(*) from ' +@tbl) = 0
PRINT 'no rows'

Its variant,
IF exists (EXEC('select count(*) from ' +@tbl)) = 0
PRINT 'no rows'
*/

Do I know more sleep :)

TIA.


Hi Nick,

I think that the most important question is: why don't you know the names
of your tables? Dynamic SQL is very rarely necessary in a well designed
database. If you feel you must use dynamic SQL, then at least read up on
the dangers of SQL injection. What if somebody sets @tbl to 'customers
drop customers'? The exec will happily count the number of rows in the
customers table, then drop it. Read www.sommarskog.se/dynamic_sql.html.

Your query is also rather inefficient. Using COUNT(*) to find if there are
zero rows means that SQL Server will just spend the time to calculate the
exact amount of rows in your 30 GB table, only to find that it's not 0. If
you use EXISTS instead, SQL Server will stop searching as soon as the
first row is found.

Finally, your queries are syntactically wrong. EXECUTE() is a statement,
not an expression. And everything included between the parentheses runs in
it's own context, so it should be a complete batch. The code below would
run - but it's still susceptible to SQL injection attacks!

EXEC ('IF EXISTS (SELECT * FROM ' + @tbl + ') PRINT ''no rows''')

Best, Hugo
--

(Remove _NO_ and _SPAM_ to get my e-mail address)
Jul 23 '05 #3
Thanks, David. The first option seems doable; as for the second one,
as you mentioned it does not seem to accurate.

Don

Jul 23 '05 #4
Hugo, here you go, assumption, assumption :) in this particular case,
we have several hundred tables for one db, one app needs ninety or so
tables from one (it has its ddl for tbl creation etc.), dts over data
from the master db. How do we verify that all ninety or so tables have
the data populated? Naturally, a script to check data in each table
would seem to make sense. And this script is not for public
consumption, yes, I'm sort of aware of sql injection attack, I don't
think it's applicable here though.

Thanks for the
EXEC ('IF not EXISTS (SELECT * FROM ' + @tbl + ') PRINT ''no rows''')
trick

The flow is not elegant though because I may need to do quite a bit
stuff after the evaluation and put them all together inside the EXEC
block seems pretty messy.

Also, good for you to refresh my memory about the speed between 'using
count(*)' and 'exists'.

Don

Jul 23 '05 #5
On 18 Jan 2005 06:55:29 -0800, NickName wrote:
Hugo, here you go, assumption, assumption :) in this particular case,

(snip)

Hi Don,

Good to hear that you're aware of the danger of SQL Injection and that
you're only using this dynamic SQL for a maintenance task.

I hope you didn't mind me bringing this up. I prefer warning about SQL
Injection even when the warning is not needed over not warning when I
should have. :-)

Best, Hugo
--

(Remove _NO_ and _SPAM_ to get my e-mail address)
Jul 23 '05 #6
Depends what you mean by accurate. Unless you can cease all inserts
(say by logging everyone out or by locking each table) the number of
rows in a table is a moving target, it's just a case of what is
acceptably up-to-date.

--
David Portas
SQL Server MVP
--

Jul 23 '05 #7
Agree, Hugo. Thank you. Don

Jul 23 '05 #8
I see your point, David, thanks. Don

Jul 23 '05 #9

d sql is a mess to me (the quotes!),
trying to change the following line
EXEC ('IF EXISTS (SELECT * FROM ' + @tbl + ') PRINT ''no rows''')
to
EXEC('If not exists(select * from '+ @tbl +') PRINT '+ @tbl +'''no
rows''')

got no where.

Jul 23 '05 #10

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

Similar topics

2
2202
by: Narayanan Sankaranarayanan | last post by:
Hi All, How do I dynamically evaluate expressions in VB.Net? Thanks in advance Narayanan Sankaranarayanan
9
5967
by: strotee76 | last post by:
What do I need to do to setTerm() for it to work properly? If you notice any other glaring issues, then please let me know. With this header file: ======================= #ifndef Polynomial_h #define Polynomial_h class Polynomial
35
1555
by: A Jafarpour | last post by:
Hi everyone, hope someone can tell if there is any way to, dynamically, build an statement and then call some functions to execute the statement. I know examples always help, so here what I am trying to accomplish: Dim myStatement as String myStatement = "Dim result as integer result= 2 * 3" now is there any way to actually let a program to treat myStatement as a statment and therefore execute whatever
0
912
by: YL | last post by:
I'm working on an expert system that allows dynamic updating of expert's knowledge and logics. I use database to store the info about how to evaluate user's responses to questionnaires. The core table called EvaluationPoint whose records have attributes(evaluation_point_id,questionnaire_id,pattern_id,config,status,...) Once a record in table EvaluationPoint been fetched, it becomes an object of class EvaluationPoint with virtual sub-type...
5
1312
by: Daniel Frey | last post by:
Hello I'd like to match a dynamic node, given as a parameter to the stylesheet. Something like: <xsl:stylesheet ...> <xsl:param name="tomatch"/> <xsl:template match="{$tomatch}"> Hallo </xsl:template>
7
2999
by: | last post by:
I have what's probably a simple page lifecycle question related to dynamically evaluating values that are placed by a repeater and dynmically placing user controls that use those values. I'm attempting to bind a user control I've written, "ImageBox", to a repeater. The user control takes a custom property, "ContentID", that will execute a database lookup and load an image.
54
3910
by: Rasjid | last post by:
Hello, I have just joined and this is my first post. I have never been able to resolve the issue of order of evaluation in C/C++ and the related issue of precedence of operators, use of parentheses. 1) "The order of evaluation of subexpressions is determined by the precedence and grouping of operators."
39
5053
by: Boltar | last post by:
Why does C do lazy evaluation for logical boolean operations but not bitwise ones? Ie: the following program prints "1 2" , not "1 1" under gcc main() { int a = 1; int b = 1; 0 && ++a;
4
530
by: aarklon | last post by:
Hi all, recently a friend asked me is there any dynamic binding in C...?? to which i answered AFAIK it is in C++ only, but he says it is valid in C. if dynamic can be implemented via function pointers in C , can anyone give an example for dynamic binding in C...??
0
8238
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8174
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
8680
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
8624
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...
0
7164
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
5565
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4082
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
4176
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1786
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.