473,698 Members | 2,452 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Dynamic SQL reading statements from table

Hi,

I'm using a 3rd-party app's back end which stores SQL statements in a
table, so I have no choice but to use dynamic SQL to call them (unless
someone else knows a workaround...)

Problem is, I can't get the statement to run properly, and I can't see
why. If I execute even a hard-coded variation like

DECLARE @sql nvarchar(MAX)
SET @sql ='SELECT foo FROM foostable'
sp_executesql @sql

I get: Incorrect syntax near 'sp_executesql' .

If I run

sp_executesql 'SELECT foo FROM foostable'

I get: Procedure expects parameter '@statement' of type 'ntext/nchar/
nvarchar'.
which I understand, as it's omitting the N converter--so if I run

sp_executesql N'SELECT foo FROM foostable'

it's fine. I don't understand why the first version fails. Is it some
sort of implicit conversion downgrading @sql? Every variation of CAST
and CONVERT I use has no effect.

This is SQL Server 2005 SP2. Thanks in advance.

May 1 '07
11 5134
Perhaps I wasn't as clear as I should have been. Regardless, the
problem is solved--turns out it wasn't just "related" to the first
problem, it *was* the first problem. That's why I'd introduced the
quotestring function, actually, because when I switched from variable
to SQL (on a more complicated query, obviously, than the example I
provided, including multiple parameter values), the string failed
without doubling its parameter quotes. And then I was seeing the
quotes around the SQL string as an output result, not a part of the
string...

In short, duh on me.

RE the security risk, I'm fully aware of it. But as is often the case
with a very sensitive db, if anyone even gains access to it in the
first place there are much bigger potential headaches than whether or
not they want to drop a nasty dynamic SQL statement on it.
On May 1, 6:13 pm, Erland Sommarskog <esq...@sommars kog.sewrote:
downwitch (downwi...@gmai l.com) writes:
Here's my version of the function:
-----------
CREATE FUNCTION uQuoteString(@s tr nvarchar(MAX)) RETURNS nvarchar(MAX)
AS
BEGIN
DECLARE @ret nvarchar(MAX),
@sq nvarchar(4)
SELECT @sq = ''''
SELECT @ret = replace(@str, @sq, @sq + @sq)
RETURN(@sq + @ret + @sq)
END
-----------
So running
DECLARE @sql nvarchar(MAX)
SET @sql ='SELECT foo FROM foostable'
SET @sql = dbo.uQuoteStrin g(@sql)
EXEC sp_executesql @sql
I now get: Incorrect syntax near 'SELECT foo FROM foostable'
Note that the error has changed, no longer referencing the stored proc
but instead the @sql argument.

I added a PRINT @sql to your SQL batch, and this is what I saw:

'SELECT foo FROM foostable'
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near 'SELECT foo FROM foostable'.

A string on its own is not legal T-SQL.

I don't really know what you want to achieve with your quotestring
function, but you put the entire SQL statement in quotes, which
certainly is not the right thing. You said you were reading statements
from a table. I don't really see why you would double any quotes in
these statements either.

Another issue is that the operation is certainly unsafe if anyone can
put statements intos this table, and you run your process with
heavy privs.

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

Books Online for SQL Server 2005 athttp://www.microsoft.c om/technet/prodtechnol/sql/2005/downloads/books...
Books Online for SQL Server 2000 athttp://www.microsoft.c om/sql/prodinfo/previousversion s/books.mspx

May 2 '07 #11
manstein (jk**********@g mail.com) writes:
cool thanks. BTW what other declarations allow the use of MAX for
size? I tried char and that did not work. That being the case, isnt
this inconsistent implemetation? MS at its best.
Since char is fixed length, char(MAX) would imply a data type which is
always 2GB in size. I suspect that such a type would do more harm than
good.

In SQL 2005 you can use varchar(MAX), nvarchar(MAX) and varbinary (MAX).
These are the successors to text, ntext and image, which now are
deprecated. The MAX types works very much like the regular
(n)varchar/binary. In difference to the old types that had lots of
limitations.

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

Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pro...ads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodinf...ons/books.mspx
May 2 '07 #12

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

Similar topics

2
2364
by: Tom | last post by:
I would like to know if an .asp case statement can contain HTML elements. I am building an application that I would like to have dynamic choices. The dynamic part would be built in the a case statment that will output based upon the value of the option evaluated. This example only shows one case statement but there are eight case statements. Thanks for any insight! Tom If Not objRs.EOF Then
3
9060
by: Steve | last post by:
Hi; I would like to read a list of tables from a temp table and then do a sql statement on each table name retrieved in a loop, ie: -- snip cursor loop where cursor contains a list of tables declare @rec_count int
4
13062
by: Tim.D | last post by:
People, I've ventured into the wonderful world of Stored Procedures. My first experience has been relatively successful however I am stuck on using host variables to specifiy actualy table or column names in a FROM clause. After many hours or reading all manner of manuals I've discovered it appears this is not possible and that in order to so I need to further venture into dynamic SQL. My present procedure is based on all static SQL...
3
2817
by: Alexandre H. Guerra | last post by:
Hello I need to process a SQL monitoring log stored in a table to group the statements that change just the constants in it. Ex: select a,b,c from table where (a = 'xyz' and b = 123 and c != '2004-10-10') or ( a like 'def%' ) select a,b,c from table where (a = 'zyx' and b = 321 and c != '2004-01-01') or ( a like '%fed' )
6
2669
by: MattC | last post by:
Hi, I'm implementing a new Business Layer in one of our applications. I'm toying with the idea of placing all the Create, Read, Update and Delete SQL in the object in question and build a dynamic SQL string using a class builder. The pros I can see are: It reduces the number of stored procs to admin. Changes to the underlying table schema does not require massive changes to
3
11227
by: sferriol | last post by:
hello is it possible with postgres 7.2 or more, to define a dynamic view. For example, i have a table with a column 'user' and i want to define a view which gives infomrations from different tables but the user has to specifie the 'user' parameter when using a select to the view sylvain
7
3386
by: serge | last post by:
How can I run a single SP by asking multiple sales question either by using the logical operator AND for all the questions; or using the logical operator OR for all the questions. So it's always either AND or OR but never mixed together. We can use Northwind database for my question, it is very similar to the structure of the problem on the database I am working on. IF(SELECT OBJECT_ID('REPORT')) IS NOT NULL DROP TABLE REPORT_SELECTION
5
12261
by: alingsjtu | last post by:
Hello, every body. When execute dynamic generated multiple OPENQUERY statements (which linkes to DB2) in SQLServer, I always got SQL1040N The maximum number of applications is already connected to the database. SQLSTATE=57030. Background: I created a linked server to DB2 8.1 database which called GRR_DB2Server. In my stored procedure p_FetchRawData, I need to read some data from this linked server GRR_DB2Server and insert them into
6
7968
by: =?ISO-8859-1?Q?Tim_B=FCthe?= | last post by:
Hi, we are building a Java webapplication using JSF, running on websphere, querying a DB2 9 on Suse Enterprise 10. The app uses JDBC and PreparedStatements only (aka dynamic SQL). Every night, there is a ETL which deletes most of the data in the database and fills it all new. We observed very bad performance for some statements that ran for minutes (The queried table is about 100,000 records and the result is about 500 rows)....
0
8678
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
9166
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...
1
8899
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
7737
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
5861
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
4621
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3052
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2333
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2007
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.