Showing posts with label view. Show all posts
Showing posts with label view. Show all posts

Tuesday, March 27, 2012

Executing Multi-lines SQL Scripts From Command-line

Hello,

I'm trying to execute a file containing few SQL statements.

CREATE VIEW test1 AS SELECT * FROM table1;
CREATE VIEW test2 AS SELECT * FROM table2;

The standard SQL way is to end a statement with semi-colon.
But doing that,it doesn't work in SQL Server.
After changing ";" to "GO", it works fine.

Is there anyway we can stick to ";" to indicate the end of statement.
I don't want to create scripts which works only in SQL Server.

Please comment.

Thanks in advance.Simon Hayes (sql@.hayes.ch) writes:
> Neither the semi-colon nor GO are 'standard' SQL. GO is recognized by the
> SQL Server client tools as a batch delimiter. The semi-colon is the Oracle
> equivalent, as far as I know.

And the ANSI equivalent. Hey, have you never seen Joe Celko's postings?
He has semi-colons all over the place.

Semicolon as a statement terminator is indeed standard SQL, and it is a
pity that Sybase way back in the 1980s settled on a semicolon-free syntax.
Microsoft added semicolons as a optional terminator in SQL7, but it would
constitute a major blow to existing code to make it mandatory. (But if
MS would supply a tool that added all missing semicolons to existing
code, it could be worth the effort.)

--
Erland Sommarskog, SQL Server MVP, sommar@.algonet.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techin.../2000/books.asp|||James (ehchn1@.hotmail.com) writes:
> I'm trying to execute a file containing few SQL statements.
> CREATE VIEW test1 AS SELECT * FROM table1;
> CREATE VIEW test2 AS SELECT * FROM table2;
> The standard SQL way is to end a statement with semi-colon.
> But doing that,it doesn't work in SQL Server.
> After changing ";" to "GO", it works fine.
> Is there anyway we can stick to ";" to indicate the end of statement.
> I don't want to create scripts which works only in SQL Server.

This is not legal T-SQL:

CREATE VIEW test1 AS SELECT * FROM table1;
go
CREATE VIEW test2 AS SELECT * FROM table2;
go

For some explicable reason ; is not permitted here. (Probably because
CREATE VIEW must be alone in a batch.

However, if you change the batch separator to with the -c option as
Simon Hayes suggested, this works:

CREATE VIEW test1 AS SELECT * FROM table1
;
CREATE VIEW test2 AS SELECT * FROM table2
;

And it still legal in ANSI-compliant engines.

Since the batch-separator must be alone on a line, this solution
can work decently. Of course if a developer for some reason puts a
lone semicolon in the middle of a stored procedure, he effectively
splits that procedure in two.
--
Erland Sommarskog, SQL Server MVP, sommar@.algonet.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techin.../2000/books.asp|||"Erland Sommarskog" <sommar@.algonet.se> wrote in message
news:Xns93D3E36904A63Yazorman@.127.0.0.1...
> Simon Hayes (sql@.hayes.ch) writes:
> > Neither the semi-colon nor GO are 'standard' SQL. GO is recognized by
the
> > SQL Server client tools as a batch delimiter. The semi-colon is the
Oracle
> > equivalent, as far as I know.
> And the ANSI equivalent. Hey, have you never seen Joe Celko's postings?
> He has semi-colons all over the place.
> Semicolon as a statement terminator is indeed standard SQL, and it is a
> pity that Sybase way back in the 1980s settled on a semicolon-free syntax.
> Microsoft added semicolons as a optional terminator in SQL7, but it would
> constitute a major blow to existing code to make it mandatory. (But if
> MS would supply a tool that added all missing semicolons to existing
> code, it could be worth the effort.)
> --
> Erland Sommarskog, SQL Server MVP, sommar@.algonet.se
> Books Online for SQL Server SP3 at
> http://www.microsoft.com/sql/techin.../2000/books.asp

Interesting, I didn't know there was any standard at all in that area. It's
a good point about Celko's posts, though, given his insistence on
platform-independent code - I guess I should have worked that one out...

Simon

Monday, March 26, 2012

Executing a Views from a Trigger

Hi,

I am new to using SQL. I want to be able to exucute a query that I
place in a view. I want this views to be executed every time a value
change in one of the table in a particular field. So my guess was to
use a trigger that will call the views every time the data change in
the selected table. Is this the proper way of doing thing? Should I
use other SQL tools to achive this. I search for exemple of trigger
executing views but did not found anything as of yet. Let's use this
dummy name for the exemple:

Database: DB1
Table: Tbl1
Special field in Tbl1: flag
Views name: views_01

Thank you.

PhilippeForgot to mention, I am using SQL 2000.

Thank you.|||Hi,

> I am new to using SQL. I want to be able to exucute a query that I
> place in a view.

You don't execute queries inside views. You just get to use the
view as if it were a table.

Why would you want to "execute the query"?

--
Martijn Tonies
Database Workbench - tool for InterBase, Firebird, MySQL, Oracle & MS SQL
Server
Upscene Productions
http://www.upscene.com
My thoughts:
http://blog.upscene.com/martijn/
Database development questions? Check the forum!
http://www.databasedevelopmentforum.com

>I want this views to be executed every time a value
> change in one of the table in a particular field. So my guess was to
> use a trigger that will call the views every time the data change in
> the selected table. Is this the proper way of doing thing? Should I
> use other SQL tools to achive this. I search for exemple of trigger
> executing views but did not found anything as of yet. Let's use this
> dummy name for the exemple:
> Database: DB1
> Table: Tbl1
> Special field in Tbl1: flag
> Views name: views_01|||Hi

What exactly do you mean by "call the views every time the data change in
the selected table."?

When the data is added/updated/deleted from the underlying table the View is
automatically updated. (It is just a select statement).

Are you concerned about updating the user interface where the View is used
as a source for a datgrid or something. If so you have to find some way to
tell the Client program to requery the database, perhaps using the View.
when a database update occurs.

--
-Dick Christoph
<solidsna2@.gmail.com> wrote in message
news:1141226630.058373.30490@.e56g2000cwe.googlegro ups.com...
> Hi,
> I am new to using SQL. I want to be able to exucute a query that I
> place in a view. I want this views to be executed every time a value
> change in one of the table in a particular field. So my guess was to
> use a trigger that will call the views every time the data change in
> the selected table. Is this the proper way of doing thing? Should I
> use other SQL tools to achive this. I search for exemple of trigger
> executing views but did not found anything as of yet. Let's use this
> dummy name for the exemple:
> Database: DB1
> Table: Tbl1
> Special field in Tbl1: flag
> Views name: views_01
> Thank you.
> Philippe|||I am working with an application that use SQL to store it's data. What
I am trying to achieve is to execute the query below every hour.

UPDATE Tbl1
SET Tbl1.Flag = '0'
WHERE Tbl1.Flag <> '0'

UPDATE Tbl1
SET Flag = '1'
WHERE Tbl1.Key = (SELECT Tbl2.Key
FROM Tbl2
WHERE Tbl2.Key = Tbl1.Key
AND CURRENT_TIMESTAMP >= Tbl2.Expdate GROUP
BY Tbl2.Key)

DELETE Tbl2
WHERE CURRENT_TIMESTAMP >= Tbl2.Expdate

The Query does exactly what I want it to do. Now I want to launch this
query from the application I was talking about earlyer. So I thought
that if I use a trigger that will be iniated by a script in my
application by changing a value to 1 or 0 every hour. This will then
activate the SQL trigger that will execute the query above. I strore
the query in a views. So that is why I ask how to execute a views with
a trigger.

Maybe this is not the way to go, but I hope you can understand what I
am trying to do.

Thank you again.

Philippe|||Hi

If you want to execute this every hour, this would be better handled in a
scheduled job. Which can be scheduled to run a SQL Statement or stored
procedure every hour.

Although you could schedule the application to run an update query (without
a Trigger or View) every hour, what if the application isn't running all the
time? or if there are muttiple instances of it running?

One point of clarification you cannot execute and Update Query in a View.

-Dick Christoph

--
<solidsna2@.gmail.com> wrote in message
news:1141233438.780742.274780@.t39g2000cwt.googlegr oups.com...
>I am working with an application that use SQL to store it's data. What
> I am trying to achieve is to execute the query below every hour.
> UPDATE Tbl1
> SET Tbl1.Flag = '0'
> WHERE Tbl1.Flag <> '0'
> UPDATE Tbl1
> SET Flag = '1'
> WHERE Tbl1.Key = (SELECT Tbl2.Key
> FROM Tbl2
> WHERE Tbl2.Key = Tbl1.Key
> AND CURRENT_TIMESTAMP >= Tbl2.Expdate GROUP
> BY Tbl2.Key)
> DELETE Tbl2
> WHERE CURRENT_TIMESTAMP >= Tbl2.Expdate
> The Query does exactly what I want it to do. Now I want to launch this
> query from the application I was talking about earlyer. So I thought
> that if I use a trigger that will be iniated by a script in my
> application by changing a value to 1 or 0 every hour. This will then
> activate the SQL trigger that will execute the query above. I strore
> the query in a views. So that is why I ask how to execute a views with
> a trigger.
> Maybe this is not the way to go, but I hope you can understand what I
> am trying to do.
> Thank you again.
> Philippe|||How do I run a SQL statement or stored procedure every hour?

It can not run the the query all the time. I am doing other
manipulation withing my application. The 2 jobs needs to be
synchronise +- 5 min.

Thank you again for the help.

Philippe|||(solidsna2@.gmail.com) writes:
> How do I run a SQL statement or stored procedure every hour?

As Dick said, schedule a job to run from SQL Server Agent.

> It can not run the the query all the time. I am doing other
> manipulation withing my application. The 2 jobs needs to be
> synchronise +- 5 min.

In SQL Agent, a job can have several steps that executed in order. This
may be something for you.

It is difficult from your abstract definition to say whether you are
on the right track at all. If you can describe the underlying business
problem, it is more likely that you will get useful advice.

--
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se

Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pr...oads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodin...ions/books.mspx

Executing a View timesout through Open View

Hello All,

I have created a view that will potentially return a huge number of records around 500,000 rows. When i execute this view by clicking Open View from the SQL Management studio i get the following error

SQL Execution error

Error Source: .Net SqlClient Data Provider
Error Message: Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding

However the query executes when paste the generated query of the view in the query designer window. It returns the 500,000 rows. I am wondering if there is some option that i will have to configure to return a large size result set in view designer. I also want to know if this is an inherent problem with view designer.

Any help regarding this will be really appreciated.

Satya

Open View creates a fully editable grid of the rows returned by the view so it is not surprising that it is choking on that much data.

First - this is not the view designer, the view designer opens when you select Modify, and that will let you edit the view definition.

If you do want to work with the data in the view through Open View, then after you select Open View, click the stop button down at the bottom of the window, next to the message that says Retrieving Data... It will stop and show whatever data it retrieved before you clicked the button. Now click the Show SQL Pane button on the toolbar (or Query Designer/Pane menu). In the SQL pane, edit the query by adding a WHERE clause to the SELECT statement that is selecting the data from you view. Now click the Execute SQL button (the exclamation mark) and it will run and return only the rows that match. Now you can selectively pull only a portion of the 500,000 rows at a time and work on them, then change the WHERE clause to select other rows. I can't believe you really want all 500,000 rows on screen at the time - and SQL Server doesn't think it's a good idea either :-)

|||

Hi,

Thanks for your reply. I didnt intend to see all the 500,000 rows of data at a time but did want to know the maximum volume that i can see when i click Open View. The stop button is also disabled when i click Open view and i get this error directly and so i cannot see a partial set of the data the way you had specified. Also i wrote <select a top 1 * > query enveloping the query generated by the view so that i could get atleast the first tuple of the query result but even this was aborted by the same error. The error comes immediately after a minute and no option is enabled for me to do anything once i click Open View or execute.

I was trying to see if this was a configuration issue in VIEW or if i was missing something else. The same query does give the intended results when i run in the query designer. Is there a capacity constraint for the Results grid pane in the View Designer as compared to normal query window.

Thanks again for your help and would appreciate if you can clarify the above too

satya

|||Do you by any chance have a TOP and an ORDER BY in the view definition, or is the view just a standard SELECT?|||It just seems that the CommandTimeout property is not updated in Management Studio when using View, and that it is always stuck at 30 sec. I have the same problem, but it seems impossible to fix.|||I have a view that returns over 500,000 rows, it takes about 5 minutes and never times out. I can click the Stop button at any time. I haven't changed anything from default so I'm not sure what's different.sql

Friday, March 23, 2012

Executing a SPROC from a View

Is it possible to execute a SPROC from within a view? If so, will the query
slow the SPROC any lower than it normally would run?
I use excel pivot charts based on sql views a good bit. As far as I know, I
don't think pivot charts can be based on SPROC's. I've run into a database
that is very large and requires a good bit of formulas in the view which
slow it down.
I'm just looking for any way to speed my data call to my excel pivot chart.Theroretically yes. But pratically and perferable, no.
You *could* use the OPENQUERY method for that, but as I said I didn=B4t
make any good experiences with that.
HTH, Jens Suessmeyer.
http://www.sqlserver2005.de
--|||Scott (sbailey@.mileslumber.com) writes:
> Is it possible to execute a SPROC from within a view? If so, will the
> query slow the SPROC any lower than it normally would run?
> I use excel pivot charts based on sql views a good bit. As far as I
> know, I don't think pivot charts can be based on SPROC's. I've run into
> a database that is very large and requires a good bit of formulas in the
> view which slow it down.
> I'm just looking for any way to speed my data call to my excel pivot
> chart.
You can use OPENQUERY that Jens mention, but it a serious kludge, and
it is not likely to speed anything else up.
Sorry, without any more information about your real problem, it's
difficult to say anything more.
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pr...oads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodin...ions/books.mspxsql

Monday, March 19, 2012

Execute UDF/extended stored procedure only through view?

Lets say I have a view, MyView, that calls MyUDF and/or MyExtendedProcedure.
Is there a way I can allow a user to access MyView, but stop them from
directly executing MyUDF or MyExtendedProcedure?
E.g., I'd like them to be able to do this:
select * from MyView
but stop them from doing this:
Exec MyExtendedStoredProcedure
Is this possible? Thanks for any tips.As long as the objects referenced by your view are owned by the same user,
permissions on indirectly referenced objects are not checked. This behavior
is known as ownership chaining. Beginning with SQL 2000 SP3, you also need
to also turn on the 'db chaining' database option (a.k.a. cross-database
chaining) when objects reside in different databases.
Also, the databases need to be owned by the same login in order to maintain
an unbroken chain for your dbo-owned objects in different databases. The
master database is owned by the 'sa' login so your user database needs to
also be owned by 'sa' to provide an unbroken ownership chain to your
dbo-owned extended stored procedure. You can use sp_changedbowner if
needed.
Note that 'db chaining' should be enabled in an sa-owned database when only
sysadmin role members have permissions to create dbo-owned objects. See
Cross DB Onership Chaining <adminsql.chm::/ad_config_8d7m.htm> in the Books
Online for more information.
Hope this helps.
Dan Guzman
SQL Server MVP
"Neil W" <neilw@.REMOVEnetlib.com> wrote in message
news:uLP5XyJ1EHA.936@.TK2MSFTNGP12.phx.gbl...
> Lets say I have a view, MyView, that calls MyUDF and/or
> MyExtendedProcedure.
> Is there a way I can allow a user to access MyView, but stop them from
> directly executing MyUDF or MyExtendedProcedure?
> E.g., I'd like them to be able to do this:
> select * from MyView
> but stop them from doing this:
> Exec MyExtendedStoredProcedure
> Is this possible? Thanks for any tips.
>
>

Sunday, February 19, 2012

Execute Package Logon Failed for User....

Fairly new to SSIS.I have created a package in BIDS, and am trying to execute it so i can test/debug the flow and view the data in the data viewers. I continually get a logon failed for user... its the user id i am using to connect to my SourceConnection OLEDB. I have been struggling with this for a while now, and getting frustrated. I tried Windows Authentication also, still i get an error message logon failed for user......

I have tried all of the security settings, from Do not save sensitive to Encrypt all with password, entered the password, and then try to Execute Package from the solution explorer and still get error message. Thanks for your help!

Here is the error message

An OLE DB record is available. Source: "Microsoft SQL Native Client" Hresult: 0x80040E4D Description: "Login failed for user 'UserName'.".

I suffered a similar problem with ado .net connection. I changed ProtectionLevel property to ServerStorage and it ran fine.

BTW, what about the log?

|||

I guess i can try that, but i like the ease of deployment having the packages file based.

What log?

|||log for that dtsx. By default ssis packages haven't. You can create one from Logging menu option|||Gotcha! thanks for that tip! Is there a package level security i can use for file based packages that is basically no security? We are not concerned about encrypting the sensitive information for this package.|||

OK I logged it to event viewer. It looks like the userid i am using to logon to the sourceconnection (SQL server native client) is also the userid that the package is failing to connect to the local (CLIENT) machine. Why is it trying to logon onto the local PC? Does the user that logs onto this local server USERID1 have to be the same as the userid we are using to logon to the SQL server database USERID2? That doesnt make sense? or does it?

|||Thanks for your help. I was able to figure this out. I was using Package configuration and in it i had selected to override the userid for the sourceconnection (SQL native client). After I took that out, and made the sourceconnection use windows authentication now i am able to execute the package. BTW i also added my local user to the SQL database users. Thanks! I am learning....

Execute Package Logon Failed for User....

Fairly new to SSIS.I have created a package in BIDS, and am trying to execute it so i can test/debug the flow and view the data in the data viewers. I continually get a logon failed for user... its the user id i am using to connect to my SourceConnection OLEDB. I have been struggling with this for a while now, and getting frustrated. I tried Windows Authentication also, still i get an error message logon failed for user......

I have tried all of the security settings, from Do not save sensitive to Encrypt all with password, entered the password, and then try to Execute Package from the solution explorer and still get error message. Thanks for your help!

Here is the error message

An OLE DB record is available. Source: "Microsoft SQL Native Client" Hresult: 0x80040E4D Description: "Login failed for user 'UserName'.".

I suffered a similar problem with ado .net connection. I changed ProtectionLevel property to ServerStorage and it ran fine.

BTW, what about the log?

|||

I guess i can try that, but i like the ease of deployment having the packages file based.

What log?

|||log for that dtsx. By default ssis packages haven't. You can create one from Logging menu option|||Gotcha! thanks for that tip! Is there a package level security i can use for file based packages that is basically no security? We are not concerned about encrypting the sensitive information for this package.|||

OK I logged it to event viewer. It looks like the userid i am using to logon to the sourceconnection (SQL server native client) is also the userid that the package is failing to connect to the local (CLIENT) machine. Why is it trying to logon onto the local PC? Does the user that logs onto this local server USERID1 have to be the same as the userid we are using to logon to the SQL server database USERID2? That doesnt make sense? or does it?

|||Thanks for your help. I was able to figure this out. I was using Package configuration and in it i had selected to override the userid for the sourceconnection (SQL native client). After I took that out, and made the sourceconnection use windows authentication now i am able to execute the package. BTW i also added my local user to the SQL database users. Thanks! I am learning....

Execute Non Query: Command Text Property has not been initialized

I get this when I delete a row then save data in a data grid view control.
Hints to fix ?Hello
This is not the best group for this problem; you will get better
answers in a .Net group, for example
microsoft.public.dotnet.framework.adonet or
microsoft.public.dotnet.datatools.
It's not my domain, but I suppose that you should check the
DeleteCommand property of the corresponding TableAdapter in the
appropriate DataSet.
Razvan

Wednesday, February 15, 2012

Execute Big Dynamic SQL in Stored Procedure to Create View

I am trying to create a dynamic SQL statement to create a view.
I have a stored procedure, which based on the parameters passed calls
different stored procedures. Each of this sub stored procedure creates
a string of custom SQL statement and returns this string back to the
main stored procedure.

This SQL statements work fine on there own. The SQL returned from the
sub stored procedure are returned fine. The datatype of the variable
that this sql is stored in Varchar(I have tried using nvarchar also
same problem).

If I have more that 6 SQL statements concated then the main SQL gets
cut off. It doesnt matter in what sequence I create the main SQL.

Here is the Stored procedure

/**********************************************/
/*Main Stored Procedure */

/**********************************************/
CREATE PROC sp_generate_invoice1 @.prev_date NVarchar(1000) ,
@.prev_month NVarchar(32)
AS

DECLARE invoice_driver_cur CURSOR FOR
Select driversid From Invoice_drivers

Open invoice_driver_cur

Declare
@.C VARCHAR(8000),
@.L_args Varchar(8000),
@.@.sqlstmt Varchar(8000),
@.L_driverid Int,
@.L_rowcount Int

SET QUOTED_IDENTIFIER ON

SET TEXTSIZE 32768

Set @.L_rowcount = 0

-- Drop the previous View
IF EXISTS (SELECT TABLE_NAME FROM INFORMATION_SCHEMA.VIEWS
WHERE TABLE_NAME = 'custom_invoice')
DROP VIEW custom_invoice

Fetch Next From invoice_driver_cur
Into @.L_driverid

-- Create the new View
Set @.L_args = N'Create View custom_invoice As'

--Select @.L_driverid

WHILE( @.@.FETCH_STATUS = 0)
BEGIN
Set @.L_rowcount = @.L_rowcount + 1
select @.L_driverid
If @.L_driverid = 2
Begin
Exec sp_invoice_driver2 @.prev_date, @.prev_month, @.@.sqlstmt Output

If @.L_rowcount > 1
Begin
Set @.C = @.L_args + ' Union ' + @.@.sqlstmt
End
Else
Begin
Set @.C = @.L_args + @.@.sqlstmt
End
End

If @.L_driverid = 3
Begin
Exec sp_invoice_driver3 @.prev_date, @.prev_month, @.@.sqlstmt Output

If @.L_rowcount > 1
Begin
Set @.C = @.C + ' Union ' + @.@.sqlstmt
End
Else
Begin
Set @.C = @.L_args + @.@.sqlstmt
End
End

If @.L_driverid = 4
Begin
Exec sp_invoice_driver4 @.prev_date, @.prev_month, @.@.sqlstmt Output

If @.L_rowcount > 1
Begin
Set @.C = @.C + ' Union ' + @.@.sqlstmt
End
Else
Begin
Set @.C = @.L_args + @.@.sqlstmt
End
End

If @.L_driverid = 5
Begin
Exec sp_invoice_driver5 @.prev_date, @.prev_month, @.@.sqlstmt Output

If @.L_rowcount > 1
Begin
Set @.C = @.C + ' Union ' + @.@.sqlstmt
End
Else
Begin
Set @.C = @.L_args + @.@.sqlstmt
End
End

If @.L_driverid = 6
Begin
Exec sp_invoice_driver6 @.prev_date, @.prev_month, @.@.sqlstmt Output

If @.L_rowcount > 1
Begin
Set @.C = @.C + ' Union ' + @.@.sqlstmt
End
Else
Begin
Set @.C = @.L_args + @.@.sqlstmt
End
End

If @.L_driverid = 7
Begin
Exec sp_invoice_driver7 @.prev_date, @.prev_month, @.@.sqlstmt Output

If @.L_rowcount > 1
Begin
Set @.C = @.C + ' Union ' + @.@.sqlstmt
End
Else
Begin
Set @.C = @.L_args + @.@.sqlstmt
End
End

If @.L_driverid = 8
Begin
Exec sp_invoice_driver8 @.prev_date, @.prev_month, @.@.sqlstmt Output

If @.L_rowcount > 1
Begin
Set @.C = @.C + ' Union ' + @.@.sqlstmt
End
Else
Begin
Set @.C = @.L_args + @.@.sqlstmt
End
End

If @.L_driverid = 10
Begin
Exec sp_invoice_driver_niku @.prev_date, @.prev_month, @.L_driverid,
@.@.sqlstmt Output

If @.L_rowcount > 1
Begin
Set @.C = @.C + ' Union ' + @.@.sqlstmt
End
Else
Begin
Set @.C = @.L_args + @.@.sqlstmt
End
End
Print @.C
Fetch Next From invoice_driver_cur
Into @.L_driverid

Continue

End
Close invoice_driver_cur
DeAllocate invoice_driver_cur

Exec (@.C)
--EXEC sp_executesql @.C
GO

/**********************************************/

/*Sub Procedure sp_invoice_driver2 */

/**********************************************/

CREATE PROC sp_invoice_driver2 @.args NVarchar(1000), @.prev_month
NVarchar(100),
@.sqlstmt Varchar(8000) Output
AS

SET QUOTED_IDENTIFIER ON

SET @.sqlstmt = ' Select 1 SortOrder ,
( SELECT Drivers.Description) Description,
(BillingReport.Active_Accounts * Cast(Fee.fee_rate As decimal(4,2)
)) / 12 Amount,
Drivers.Currency
FROM BillingReport, Drivers, Fee
WHERE ( Fee.Driverid = Drivers.Driversid ) and
Drivers.Driversid = 2 and
billingreport.fromdate = ''' + Cast(@.args As NVARCHAR(20)) + '''
and
fee.currentmonth = ''' + Cast(@.prev_month As NVARCHAR(12)) +' '''

GO

/**********************************************/

This is what the Print Statement give:

/**********************************************/

Create View custom_invoice As Select 1 SortOrder ,
( SELECT Drivers.Description) Description,
(BillingReport.Active_Accounts * Cast(Fee.fee_rate As decimal(4,2)
)) / 12 Amount,
Drivers.Currency
FROM BillingReport, Drivers, Fee
WHERE ( Fee.Driverid = Drivers.Driversid ) and
Drivers.Driversid = 2 and
billingreport.fromdate = '9/1/2004' and
fee.currentmonth = 'September ' Union Select 2,
(SELECT Drivers.Description),
(BillingReport.Zero_Balance * Cast(Fee.fee_rate As decimal(9,2) ))
/ 12 Amount,
Drivers.Currency
FROM BillingReport, Drivers, Fee
WHERE ( Fee.Driverid = Drivers.Driversid ) and
billingreport.fromdate = '9/1/2004' and
fee.currentmonth = 'September' and
Drivers.Driversid = 3 Union Select 3,
(Select Drivers.Description From Drivers Where DriversID = 4),
Count(*) * Cast((select fee.fee_rate
from fee, drivers
where Fee.Driverid = Drivers.Driversid and
fee.currentmonth = 'September' and
Drivers.Driversid = 4 )As decimal(6,2)) / 12,
(Select Drivers.Currency
From Drivers Where DriversID = 4)
From Fund Union Select 4,
(Select Drivers.Description From Drivers Where DriversID = 5),
(((Sum(BillingReport.Man_Reg_Purch + BillingReport.Man_Reg_Red +
BillingReport.Man_Reg_Transexch +
BillingReport.Man_Allo_Purch +
BillingReport.Man_Allo_Red +
BillingReport.Man_Allo_Transexch +
BillingReport.Man_Allo_Adj_Purch +
BillingReport.Man_Allo_Adj_Red +
BillingReport.Man_Allo_Adj_Transexch +
BillingReport.Man_Adj_Purch +
BillingReport.Man_Adj_Red +
BillingReport.Man_Adj_Transexch ) ) +
(Select Sum(Cast(satuscnt As int ))
From Awd_stub
Where CurrentMonth = 'September'))) *
(Cast((select fee.fee_rate
from fee, drivers
where Fee.Driverid = Drivers.Driversid and
fee.currentmonth = 'September' and
Drivers.Driversid = 5 )As decimal(6,2))),
(Select Drivers.Currency From Drivers Where DriversID = 5)
FROM BillingReport
Where billingreport.fromdate = '9/1/2004' Union Select 5,
(Select Drivers.Description From Drivers Where DriversID = 6),
( Sum( BillingReport.Auto_Reg_Purch +
BillingReport.Auto_Reg_Red +
BillingReport.Auto_Reg_TRansexch +
BillingReport.Auto_Allo_Purch+
BillingReport.Auto_Allo_Red +
BillingReport.Auto_Allo_Transexch+
BillingReport.Auto_Allo_Adj_Purch+
BillingReport.Auto_Allo_Adj_Red+
BillingReport.Auto_Allo_Adj_transexch+
BillingReport.Auto_Adj_Purch+
BillingReport.Auto_Adj_Red+
BillingReport.Auto_Adj_Transexch )+
(Select Sum(Cast(Processed_msg As Int))
From XML_messaging
Where CurrentMonth = 'September'))*
(Cast((select fee.fee_rate
from fee, drivers
where Fee.Driverid = Drivers.Driversid and
fee.currentmonth = 'September' and
Drivers.Driversid = 6 )As decimal(6,2))),
(Select Drivers.Currency From Drivers Where DriversID = 6)
FROM BillingReport
Where billingreport.fromdate = '9/1/2004' Union Select 6,
(Select Drivers.Description From Drivers Where DriversID = 7),
( ( a.Accountholder_Active_Accounts -
(select accountholder_active_accounts from billingreport where
Month(fromdate) = Month('9/1/2004')-1 ) )
+
( a.Accountholder_Zero_Balance -
(select accountholder_zero_balance from billingreport where
Month(fromdate) = Month('9/1/2004')-1 ))) *
(Cast((select fee.fee_rate
from fee, drivers
where Fee.Driverid = Drivers.Driversid and
fee.currentmonth = 'September' and
Drivers.Driversid = 7 )As decimal(6,2))),
(Select Drivers.Currency From Drivers Where DriversID = 7)
FROM BillingReport a Where a.fromdate = '9/1/2004' Union Select 7,
(Select Drivers.Description From Drivers Where DriversID = 8),
( Select telephone From cfxbill Where currentmonth = 'September') *
(Cast((select fe

Thanks for any help
MDThis is the worst use of SQL I have ever seen in 18 years of
programming in the language. If I put this in my next book, nobody
would believe it was real.

>> I am trying to create a dynamic SQL statement to create a view. <<

Which completely defeats the purpose of a VIEW and does it by using
the worst possible approach for production code. Dynamic SQL says that
you have no idea what your own schema should look like, so you assume
that any random user sometime in the future is going to do a better
job.

>> I have a stored procedure, which based on the parameters passed
calls different stored procedures. Each of this sub stored procedure
creates a string of custom SQL statement and returns this string back
to the main stored procedure. <<

Ever have a course in Software Engineering? Obviously not. I cannot
take the time to go over all the probldms with this approach; just get
a book on SE and read it. This has nothing to do with SQL per se, but
with the very **basics** of your trade.

I tried for almost an hour to just read and understand your code. How
do you expect anyone to maintain it? Your inconsistent
capitalization, failure to use alias table names and use of tabs in
the code was also a pain to the reader.

>> If I have more that 6 SQL statements concated then the main SQL
gets cut off. It doesn't matter in what sequence I create the main
SQL. <<

You are probably generating so much crappy code that you are
overflowing the limits of SQL Server.

Did you know that T-SQL was never meant to be an application
development language? As best I can figure out, this nightmare is a
UNION-ed mess of unrelated reports. Break it apart into VIEWs --
**real** VIEWs that are part of the schema, and not this
conglomeration of confused reports. Get rid of the hard-wired date;
if you want to write a stored procedure, you can make it a parameter.
Get rid of the string month name; in a tiered architecture, display is
done in the front end, not the database (again, that has nothign to do
with SQL per se, but is just a basic progrmaming principle).

Try things more like this:

CREATE VIEW Driver_2_invoice (description, from_date, amount,
currency)
AS
SELECT D1.description,
B1.from_date,
(B1.active_accounts * F1.fee_rate)/12.00,
D1.currency
FROM BillingReports AS B1, Drivers AS D1, Fee AS F1
WHERE F1.driver_id = 2
AND D1.driver_id = 2;

But did you notice that "BillingReports" is CROSS JOIN-ed? When you
use the VIEW, you apply a from_date to it to get the range you want.

and so on for the other UNION-ed queries.

CREATE VIEW Driver_3_invoice (description, from_date, amount,
currency)
AS
SELECT D1.description, B1.from_date,
B1.zero_balance * F1.fee_rate) / 12.00,
D1.currency
FROM BillingReport AS B1, Drivers AS D1, Fee AS F1
WHERE F1.driver_id = 3
AND D1.driver_id = 3;

Etc.

If this is how you are writing queries, it is a pretty good bet that
the DDL is also a nightmare of bad datatypes, lack of constraints and
so forth.|||jcelko212@.earthlink.net (--CELKO--) wrote in message news:<18c7b3c2.0410201422.21deda06@.posting.google.com>...
> This is the worst use of SQL I have ever seen in 18 years of
> programming in the language. If I put this in my next book, nobody
> would believe it was real.
> >> I am trying to create a dynamic SQL statement to create a view. <<
> Which completely defeats the purpose of a VIEW and does it by using
> the worst possible approach for production code. Dynamic SQL says that
> you have no idea what your own schema should look like, so you assume
> that any random user sometime in the future is going to do a better
> job.
> >> I have a stored procedure, which based on the parameters passed
> calls different stored procedures. Each of this sub stored procedure
> creates a string of custom SQL statement and returns this string back
> to the main stored procedure. <<
> Ever have a course in Software Engineering? Obviously not. I cannot
> take the time to go over all the probldms with this approach; just get
> a book on SE and read it. This has nothing to do with SQL per se, but
> with the very **basics** of your trade.
> I tried for almost an hour to just read and understand your code. How
> do you expect anyone to maintain it? Your inconsistent
> capitalization, failure to use alias table names and use of tabs in
> the code was also a pain to the reader.
> >> If I have more that 6 SQL statements concated then the main SQL
> gets cut off. It doesn't matter in what sequence I create the main
> SQL. <<
> You are probably generating so much crappy code that you are
> overflowing the limits of SQL Server.
> Did you know that T-SQL was never meant to be an application
> development language? As best I can figure out, this nightmare is a
> UNION-ed mess of unrelated reports. Break it apart into VIEWs --
> **real** VIEWs that are part of the schema, and not this
> conglomeration of confused reports. Get rid of the hard-wired date;
> if you want to write a stored procedure, you can make it a parameter.
> Get rid of the string month name; in a tiered architecture, display is
> done in the front end, not the database (again, that has nothign to do
> with SQL per se, but is just a basic progrmaming principle).
> Try things more like this:
> CREATE VIEW Driver_2_invoice (description, from_date, amount,
> currency)
> AS
> SELECT D1.description,
> B1.from_date,
> (B1.active_accounts * F1.fee_rate)/12.00,
> D1.currency
> FROM BillingReports AS B1, Drivers AS D1, Fee AS F1
> WHERE F1.driver_id = 2
> AND D1.driver_id = 2;
> But did you notice that "BillingReports" is CROSS JOIN-ed? When you
> use the VIEW, you apply a from_date to it to get the range you want.
> and so on for the other UNION-ed queries.
> CREATE VIEW Driver_3_invoice (description, from_date, amount,
> currency)
> AS
> SELECT D1.description, B1.from_date,
> B1.zero_balance * F1.fee_rate) / 12.00,
> D1.currency
> FROM BillingReport AS B1, Drivers AS D1, Fee AS F1
> WHERE F1.driver_id = 3
> AND D1.driver_id = 3;
> Etc.
> If this is how you are writing queries, it is a pretty good bet that
> the DDL is also a nightmare of bad datatypes, lack of constraints and
> so forth.

Thank you for your comments. I will get a book on SE and follow some
of your pointer. I understand that you have written a numerous books
on SQL but surely there is not need to be rude! I have overlooked the
alias part but without even knowing what my user requirements are try
not to pass judgement. Again thank you for your feed back considering
that you had to waste 1 hr going through my code. For sure I am going
to buy one of your books, which one would you recommend?|||>> I will get a book on SE and follow some
of your pointer. <<

The classics are by Yourdon, DeMacro and Constantine. I also like Gane
& Sarson for systems level stuff -- IST is a better diagramming method
than Yourdon.

>> I understand that you have written a numerous books
on SQL but surely there is not need to be rude! <<

My wife is the fukatan at a Zen monastary; they beat their students with
sticks :)

>> For sure I am going to buy one of your books, which one would you
recommend? <<

SQL FOR SMARTIES is the classic that most SQL programmer have on their
desk with post-it notes sticking out of it. It is a collection of SQL
programming techniques. I will start work on the third edition next
month, but I have no idea when it will come out; certainly not until
2005.

my DATA & DATABASES is a good look at foundations and some hueristics
for database in general. Pay attention to scales and measurements and
the design of encoding schemes; I seem to be the only guy who talks
about how to actually design data representations as opposed to
databases.

Terry Halpin's ORM book is great for data modeling.

if you want a mental workout to see if you are getting the idea of
thinking in sets, I also have a SQL PUZZLES & ANSWERS book. Sales were
lousy, but teachers keep using it for homework assignments.

--CELKO--
Please post DDL, so that people do not have to guess what the keys,
constraints, Declarative Referential Integrity, datatypes, etc. in your
schema are. Sample data is also a good idea, along with clear
specifications.

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!|||[posted and mailed, please reply in news]

MD (mdaptardar@.ifdsgroup.com) writes:
> I am trying to create a dynamic SQL statement to create a view.
> I have a stored procedure, which based on the parameters passed calls
> different stored procedures. Each of this sub stored procedure creates
> a string of custom SQL statement and returns this string back to the
> main stored procedure.
> This SQL statements work fine on there own. The SQL returned from the
> sub stored procedure are returned fine. The datatype of the variable
> that this sql is stored in Varchar(I have tried using nvarchar also
> same problem).
> If I have more that 6 SQL statements concated then the main SQL gets
> cut off. It doesnt matter in what sequence I create the main SQL.

Supposedly the SQL statement by then exceeds 8000 characters.

The usual remedy is to have more than one SQL variable:

EXEC(@.sql1 + @.sql2 + @.sql3 + ...)

But since you are in a loop, this is not possible. In the next version of
SQL Server, currently in Beta, there is a simple solution: use the new
varchar(MAX) datatype. Here you can fit in 2GB of SQL. Alas, in SQL 2000
you only have the text data type which you cannot assign to.

But there is a solution: insert all the SQL Segments into a temp table:

CREATE TABLE #sql(id int IDENTITY, sql varchar(8000) NOT NULL)

Now loop over this table and for each row append to two variables:

SELECT @.a = '' -- Init
SELECT @.b = 'EXEC('
...
SELECT @.a = @.a + 'DELCARE @.sql' + ltrim(str(id)) + ' varchar(8000)
SELECT @.sql = ' + sql,
@.b = @.b + '@.sql' + ltrim(str(id)) + ' + '
FROM #sql
WHERE id = @.id
...
-- Final
SELECT @.b = @.b + '')'

EXEC(@.a + @.b)

That is @.a + @.b builds a an batch that in its turn calls EXEC() to create
your view.

I hope that you by now realise that you have all reason to reconsider your
design.

--
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se

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