Tuesday, March 27, 2012
easy trigger
insert into person values (... bla bala bal)
trigger is autommaticaly fired.
The trigger must log sql commads, so i must insert into table log this command, whos execute triger - insert into person values (... bla bala bal).
How I can do it?Make sure your database is set to allow cascading triggers, then your trigger should be able to both log its own insert and initiate other inserts.
blindman|||This in no problem.
Problem is:
How to find out what statement is making the trigger run and get this statement in trigger code
Originally posted by blindman
Make sure your database is set to allow cascading triggers, then your trigger should be able to both log its own insert and initiate other inserts.
blindman|||The trigger has no idea what caused the insert, update, or delete. The best you can do is reference some of the nyladic functions (look them up) that return login and user information. Then you can at least see WHO or WHAT LOGIN initiated the process.
blindman|||Well...you can tell what type...
INSERT: Rows in inserted, none in deleted
DELETE: Rows in deleted, mone in inserted
UPDATE: Rows in both
...|||The following example uses a table called PARENT as the base for INSERT TRIGGER:
if object_id('dbo.tblLog') is not null
drop table dbo.tblLog
go
create table dbo.tblLog (
EventType varchar(15) null,
Parameters int null,
EventInfo varchar(8000) null)
go
if object_id('dbo.trig_parent') is not null
drop trigger dbo.trig_parent
go
create trigger dbo.trig_parent on dbo.parent for insert as
set nocount on
declare @.cmd varchar(8000)
set @.cmd = 'create table #tbl (
EventType varchar(15) null,
Parameters int null,
EventInfo varchar(8000) null);'
set @.cmd = @.cmd + 'insert #tbl '
set @.cmd = @.cmd + 'exec ('
set @.cmd = @.cmd + char(39)+'dbcc inputbuffer (' + cast(@.@.spid as varchar(25)) + ') '
set @.cmd = @.cmd + 'with no_infomsgs' + char(39)
set @.cmd = @.cmd + ');'
set @.cmd = @.cmd + 'insert dbo.tblLog select * from #tbl'
exec (@.cmd)
go
Easy Stuff
-PatP|||thnx Pat...|||That didn't hurt much, now did it ?!?!
Anywho, while I'm sure that somebody here could have answered your question, why bother to ask here when there are oodles of folks that are readily available that can answer you? Better still, they can offer lots of insight because they actually USE MS-Access as their tool of choice.
-PatP
Thursday, March 22, 2012
Easy Insert Statement ... Hopefully!
In Oracle I have an insert statement where Im selecting from one table and isnerting into another. One of the columns Im inserting is the current date/time
Ex.
Insert Into NEW_TABLE
Select DISTINCT REGION_ID,' SBA','Standard Rule','Upgrade',SYSDATE,'1'
from REGION;
In SQL Server 2005 I cannot seem to find the right fit for the SYSDATE command: Please help
Insert Into NEW_TABLE
Select DISTINCT REGION_ID,' SBA','Standard Rule','Upgrade',?,'1'
from REGION;
use GETDATE()If you can use the same datetime for every row I would do this because it is much faster:
DECLARE @.curdate DATETIME
SET @.curdate = GETDATE()
Select DISTINCT REGION_ID,' SBA','Standard Rule','Upgrade',@.curdate,'1'
from REGION;
|||AND not subject ot time variations.|||
Great!!! Exactly what I was looking for
Thanks
Easiest way of combining multiple fields from different records into one record?
CREATE TABLE theLiterals (
theKey varchar (255) NOT NULL ,
theValue varchar (255) NULL
)
INSERT INTO theLiterals VALUES('defaultServer','\\MyServer\')
INSERT INTO theLiterals VALUES('defaultShare','MyShare\')
INSERT INTO theLiterals VALUES('defaultFolder','MyFolder\')
INSERT INTO theLiterals VALUES('defaultFile','MyFile.dat')
I then try;
SELECT
defaultServer = CASE WHEN theKey = 'defaultServer' THEN theValue END,
defaultShare = CASE WHEN theKey = 'defaultShare' THEN theValue END,
defaultFolder = CASE WHEN theKey = 'defaultFolder' THEN theValue END,
defaultFile = CASE WHEN theKey = 'defaultFile' THEN theValue END
FROM theLiterals
and I get;
defaultServer defaultShare defaultFolder defaultFile
\\MyServer\ NULL NULL NULL
NULL MyShare\ NULL NULL
NULL NULL MyFolder\ NULL
NULL NULL NULL MyFile.dat
but I want it COALESCEd like this;
defaultServer defaultShare defaultFolder defaultFile
\\MyServer\ MyShare\ MyFolder\ MyFile.dat
...but my syntax is incorrect. Is there an efficient way of doing this.
I want to have a script/UDF where I can say...
GetLiteralsFor('defaultServer','defaultShare','def aultFolder','defaultFile')
and then my one-row recordset will be...
RS(0) will = '\\MyServer\'
RS(1) will = 'MyShare\'
RS(2) will = 'MyFolder\'
RS(3) will = 'MyFile.dat'
Thanks for any help!Just add MIN():
SELECT
defaultServer = MIN(CASE WHEN theKey = 'defaultServer' THEN theValue END),
defaultShare = MIN(CASE WHEN theKey = 'defaultShare' THEN theValue END),
defaultFolder = MIN(CASE WHEN theKey = 'defaultFolder' THEN theValue END),
defaultFile = MIN(CASE WHEN theKey = 'defaultFile' THEN theValue END)
FROM theLiterals
--
David Portas
SQL Server MVP
--|||Hi
Maybe:
SELECT A.defaultServer, B.defaultShare, C.defaultFolder, D.defaultFile
FROM
( SELECT theValue AS defaultServer
FROM theLiterals
WHERE theKey = 'defaultServer' ) A,
( SELECT theValue AS defaultShare
FROM theLiterals
WHERE theKey = 'defaultShare' ) B,
( SELECT theValue AS defaultFolder
FROM theLiterals
WHERE theKey = 'defaultFolder' ) C,
( SELECT theValue AS defaultFile
FROM theLiterals
WHERE theKey = 'defaultFile' ) D
OR
SELECT
( SELECT theValue
FROM theLiterals
WHERE theKey = 'defaultServer' ) AS defaultServer ,
( SELECT theValue
FROM theLiterals
WHERE theKey = 'defaultShare' ) AS defaultShare ,
( SELECT theValue
FROM theLiterals
WHERE theKey = 'defaultFolder' ) AS defaultFolder ,
( SELECT theValue
FROM theLiterals
WHERE theKey = 'defaultFile' ) AS defaultFile
You should put a unique or primary key on theKey to make sure only one row
is returned.
John
"Steve" <steve.lin@.cognizantdesign.com> wrote in message
news:27b20cea.0407090955.690c2c8b@.posting.google.c om...
> I have a table;
> CREATE TABLE theLiterals (
> theKey varchar (255) NOT NULL ,
> theValue varchar (255) NULL
> )
> INSERT INTO theLiterals VALUES('defaultServer','\\MyServer\')
> INSERT INTO theLiterals VALUES('defaultShare','MyShare\')
> INSERT INTO theLiterals VALUES('defaultFolder','MyFolder\')
> INSERT INTO theLiterals VALUES('defaultFile','MyFile.dat')
>
> I then try;
> SELECT
> defaultServer = CASE WHEN theKey = 'defaultServer' THEN theValue END,
> defaultShare = CASE WHEN theKey = 'defaultShare' THEN theValue END,
> defaultFolder = CASE WHEN theKey = 'defaultFolder' THEN theValue END,
> defaultFile = CASE WHEN theKey = 'defaultFile' THEN theValue END
> FROM theLiterals
> and I get;
> defaultServer defaultShare defaultFolder defaultFile
> \\MyServer\ NULL NULL NULL
> NULL MyShare\ NULL NULL
> NULL NULL MyFolder\ NULL
> NULL NULL NULL MyFile.dat
> but I want it COALESCEd like this;
> defaultServer defaultShare defaultFolder defaultFile
> \\MyServer\ MyShare\ MyFolder\ MyFile.dat
> ...but my syntax is incorrect. Is there an efficient way of doing this.
> I want to have a script/UDF where I can say...
GetLiteralsFor('defaultServer','defaultShare','def aultFolder','defaultFile')
> and then my one-row recordset will be...
> RS(0) will = '\\MyServer\'
> RS(1) will = 'MyShare\'
> RS(2) will = 'MyFolder\'
> RS(3) will = 'MyFile.dat'
> Thanks for any help!|||How about this:
SELECT TOP 1
defaultServer = (SELECT theValue FROM #theLiterals
WHERE theKey = 'defaultServer'),
defaultShare = (SELECT theValue FROM #theLiterals
WHERE theKey = 'defaultShare'),
defaultFolder = (SELECT theValue FROM #theLiterals
WHERE theKey = 'defaultFolder'),
defaultFile = (SELECT theValue FROM #theLiterals
WHERE theKey = 'defaultFile')
FROM #theLiterals
That returns the desired record:
\\MyServer\MyShare\MyFolder\MyFile.dat
Or you could create a function that takes 4 parameters like 'defaultServer'
and returns a one-record table populated with the results from those 4
SELECTs.
Jim Geissman|||Missed the beginning of this thread, but if #theLiterals is not trivially
small,
you get an (avg) 2:1 speedup by doing:
SELECT
defaultServer = max(case theKey when 'defaultServer' then theValue
end)
,defaultShare = max(case theKey when 'defaultShare' then theValue
end)
,defaultFolder = max(case theKey when 'defaultFolder' then theValue
end)
,defaultFile = max(case theKey when 'defaultFile' then theValue
end)
FROM #theLiterals
"Jim Geissman" <jim_geissman@.countrywide.com> wrote in message
news:b84bf9dc.0407091511.6338405b@.posting.google.c om...
> How about this:
> SELECT TOP 1
> defaultServer = (SELECT theValue FROM #theLiterals
> WHERE theKey = 'defaultServer'),
> defaultShare = (SELECT theValue FROM #theLiterals
> WHERE theKey = 'defaultShare'),
> defaultFolder = (SELECT theValue FROM #theLiterals
> WHERE theKey = 'defaultFolder'),
> defaultFile = (SELECT theValue FROM #theLiterals
> WHERE theKey = 'defaultFile')
> FROM #theLiterals
> That returns the desired record:
> \\MyServer\ MyShare\ MyFolder\ MyFile.dat
> Or you could create a function that takes 4 parameters like
'defaultServer'
> and returns a one-record table populated with the results from those 4
> SELECTs.
> Jim Geissman|||And first place for minimum reads goes to David Portas!
Thanks everyone for the help. I originally thought doing an aggregate
function
to get rid of NULLS would be inefficient, but by looking at the TRACE
it looks
like it has the most efficient execution plan.
FYI, I listed each of your solutions and the number of reads each
took and some additional questions.
NOTE: The 'theLiterals' table would never be big enough to cause more
than a seconds execution but it is always best to strive for
efficiency anyway. I hope you agree.
-- David Portas
-- 6 reads
-- Warning: Null value is eliminated by an aggregate or other SET
operation.
-- Why is MIN so much faster than MAX?
SELECT
defaultServer = MIN(CASE WHEN theKey = 'defaultServer' THEN theValue
END),
defaultShare = MIN(CASE WHEN theKey = 'defaultShare' THEN theValue
END),
defaultFolder = MIN(CASE WHEN theKey = 'defaultFolder' THEN theValue
END),
defaultFile = MIN(CASE WHEN theKey = 'defaultFile' THEN theValue
END)
FROM theLiterals
-- Mischa Sandberg
-- 18 reads
-- Warning: Null value is eliminated by an aggregate or other SET
operation.
-- Why is MIN so much faster than MAX or is it the way the CASE-WHEN
is
-- formatted?
SELECT
defaultServer = max(case theKey when 'defaultServer' then theValue
end)
,defaultShare = max(case theKey when 'defaultShare' then theValue
end)
,defaultFolder = max(case theKey when 'defaultFolder' then theValue
end)
,defaultFile = max(case theKey when 'defaultFile' then theValue
end)
FROM theLiterals
-- John Bell
-- 24 reads
SELECT
( SELECT theValue FROM theLiterals WHERE theKey = 'defaultServer' ) AS
defaultServer ,
( SELECT theValue FROM theLiterals WHERE theKey = 'defaultShare' ) AS
defaultShare ,
( SELECT theValue FROM theLiterals WHERE theKey = 'defaultFolder' ) AS
defaultFolder ,
( SELECT theValue FROM theLiterals WHERE theKey = 'defaultFile' ) AS
defaultFile
-- John Bell
-- 24 reads
SELECT A.defaultServer, B.defaultShare, C.defaultFolder,
D.defaultFile
FROM
( SELECT theValue AS defaultServer FROM theLiterals WHERE theKey =
'defaultServer' ) A,
( SELECT theValue AS defaultShare FROM theLiterals WHERE theKey =
'defaultShare' ) B,
( SELECT theValue AS defaultFolder FROM theLiterals WHERE theKey =
'defaultFolder' ) C,
( SELECT theValue AS defaultFile FROM theLiterals WHERE theKey =
'defaultFile' ) D
-- Jim Geissman
-- 80 reads
-- Taking off the outside 'FROM theLiterals' returns only the one
record rather
-- than four duplicate records. Therefore the TOP function is then
not needed.
-- So the query becomes the same as John Bell's above with 24 reads
SELECT TOP 1
defaultServer = (SELECT theValue FROM theLiterals WHERE theKey =
'defaultServer'),
defaultShare = (SELECT theValue FROM theLiterals WHERE theKey =
'defaultShare'),
defaultFolder = (SELECT theValue FROM theLiterals WHERE theKey =
'defaultFolder'),
defaultFile = (SELECT theValue FROM theLiterals WHERE theKey =
'defaultFile')
FROM theLiterals
Sunday, March 11, 2012
Dynamically generate where condition
If we have a pre-defined SQL statement without "where conditions", how do I dynamically insert the where conditions into it (by user input or whatever)? Is there any free tool available for carrying out this kind of work?
Regards,
Ricky.
Ricky,
If the Where condition must be added to a Sql statement say within a Stored Procedure,
then you could use dynamic SQL statements.
declare @.sql varchar(255),
Select @.sql ="Predefined SQL statement" + "The where condition which can be input to the SP"
Exec @.sql
Sandoty
|||Be cautious when you use the dynamic sql queries. It may cause two preaches,
1. SQL Injection
2. Permission issues
SQL Injection,
Your code is allowing the end user to inject the SQL command on your own code. So they can vulnerable your database be cautious here. Try to eliminate the comments (-- or /**/) as your input. You can control it on the UI itself. There are lots more practices are there. Google it for SQL Injection. You will get better idea.
Permission Issues,
Dynamic sql will expect the required permission on the source tables, if current user doesn’t have the permission on the table level (but on the SP), the dynamic SQL won’t work.
You can achieve the filter conditions from the SPs or prepared query itself. If the intention is reducing the code & time to achieve this task Pls take care the above issues.
|||One more point about dynamic queries is the performance issues.
Each time you want to run them the sql command has to be recompiled in order to get an execution plan.
This may be positive in some situations. But most of the time the best way is to set your application to run with specific queries.|||You can find a lot of information about this theme in the following articles.
The Curse and Blessings of Dynamic SQL
http://www.sommarskog.se/dynamic_sql.html
Dynamic Search Conditions in
Friday, March 9, 2012
Dynamically create an SSIS Bulk Insert Package
I am looking high and low for some assistance with developing a VB .NET solution that I programmatically create a package and add tasks. I am adding a BULK INSERT task to load large FLAT TEXT files into SQL Server 2005 tables. When I execute the application I execute a package validation and it always returns FAILURE. I have been reading and searching like crazy and I have bought 2 microsoft books, TO NO AVAIL! Can anyone PLEASE help me with this. Thank you!
Cheers~
Do you have any more specific messages other than "FAILURE"?|||No, unfortunately not. This is a new venture for me and I am not even sure that I am going about the creation process correctly. Quite honestly, I am getting 'pieces' of code from different places off of Microsofts Books Online and sort of putting them together. I have been able to successfully load a package template and execute it successfully, but creating the package from scratch has proven to be quite the challenge. I have found a plethora of samples in C#, but I have not been able to locate a full sample in VB .NET at this point.
The reason I only get a 'FAILURE' return is because I am simply saying DTSExecResult = pkg.execute() and then displaying the return value of the result.
Any suggestions, guidance or direction will be GREATLY appreciated at this point! Thanks a million!
Cheers~
|||Be sure to enable logging: http://technet.microsoft.com/en-us/library/ms136023.aspxAlso know that I'm not going to be much help with the coding. I'm learning on my own as well, but I'm just trying to gather specific information for others who will read this thread.
Also know that at some point you may be asked to share your code.|||
I will gladly share my code! Thank you so much for the replies thus far. I am hoping that I can get some great responses and learn as much as possible in the coming days about this topic. Talk to you soon!
Cheers~
|||Try saving the package (Application.SaveToXML) after creating it. Then open and run the package in BIDS. That makes it a lot easier to see what the problem is.|||John, I am about to do this. However, what do you mean by running it in BIDS? Thanks.
Cheers~
|||Business Intelligence Development Studio -- or Visual Studio -- which is where you develop SSIS packages via the GUI.|||OK, what I am seeing now is that the Destination connection is not available, and there are no columns mapped from the input source - (flat file) - to the ole destination table. I am assuming that this is because I am failing to do something correctly in the code to setup the package's BULK INSERT properties.
Are there any tutorials available to understand how to set all the properties for source and destinations, respectively? Any direction you might can provide is awesome!!!!
Again, I am finding bits and pieces here and there, but nothing that says "Hey, do it this way"...
Cheers~
|||OK, I have made some progress. I now have a Flat FIle source and an OLEDB destination. My delimma at this point is mapping the SOURCE columns from the flat file to the DESTINATION columns of the OLEDB table. The Flat File does not have a header row and it is a pipe "|" delimited file. Any idea on how to map the source / destination columns?
Cheers~
|||Do you have Output columns in the Flat FIle Source output? Save the package in code (example http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=2179817&SiteID=1) and open it to check what it looks like.
If so then you should be able to connect the output to the destination's input, and select your columns. Mapping is a simple method call, but what you map to what is your logic really. In this example I just use index position becuase I "know" that my source and destination formats match.
Dynamically Changing the length of a varchar(n) field
I have a question about dynamically changing the length of a varchar(n)
field, in case the value I'm trying to insert is too big and will give
a "truncated" error, but before the error is given! i.e. Is there some
kind of a way to "test" the length of the field while Inserting the
value into it, and to have it automatically increase its length to the
length of the value being inserted, in case the value is too big?
I've been able to do this in a "primitive" way, simply by identifying
the specific error number in case the value is being truncated, and
then increasing the length of the varchar(n) field by using the ALTER
command, and then duplicating the insert statement, but is there a
standard (shorter) way of doing this?
Here is my code (I'm working in an ASP environment):
<%
var_txt = "abcdefghijklmnopqrstuvwxyz12345678789"
sql = "Insert Into Table1 (text) Values ('" & var_txt & "')"
On Error Resume Next
conn.Execute sql
If err = -2147217833 Then
Response.Write "Error Recognized Successfully!<br /><br />"
sql = "ALTER TABLE Table1 ALTER COLUMN text VARCHAR(" &
Len(var_txt) &
") NOT NULL"
On Error Resume Next
conn.Execute sql
If err<>0 Then
Response.Write "Error while trying to alter Column:<br
/>" & err & "
= " & err.description & "<br />"
Else
Response.Write "Column altered successfully to: " &
Len(var_txt) &
"<br />"
sql = "Insert Into Table1 (text) Values ('" & var_txt &
"')"
On Error Resume Next
conn.Execute sql
If err<>0 Then
Response.Write "<br />Error number 2:<br />" &
err.description &
"<br />"
Else
Response.Write "Now it was added successfully!
HaHa!<br />"
End If
End If
Else
Response.Write "Success."
End If
%>
Thanks in advance!On 26.12.2006 12:46, John wrote:
Quote:
Originally Posted by
I have a question about dynamically changing the length of a varchar(n)
field, in case the value I'm trying to insert is too big and will give
a "truncated" error, but before the error is given! i.e. Is there some
kind of a way to "test" the length of the field while Inserting the
value into it, and to have it automatically increase its length to the
length of the value being inserted, in case the value is too big?
>
I've been able to do this in a "primitive" way, simply by identifying
the specific error number in case the value is being truncated, and
then increasing the length of the varchar(n) field by using the ALTER
command, and then duplicating the insert statement, but is there a
standard (shorter) way of doing this?
There are several things to say to this. First, the length of a VARCHAR
column should generally be dependent on business requirements - i.e. the
length comes before the inserted values. You can view it as a
requirement (for example a zip code is just 5 characters here in
Germany) and data not satisfying that requirement basically should not
go into that column. In this case the table will only change if the
business requirement changes (they changed length of zip code from 4 to
5 after the wall broke down over here) and not according to data inserted.
Having said that the easiest solution in your case (i.e. if you want to
maintain that you have to insert strings with arbitrary length) is to
just set the length to the max length allowed for that column (in SQL
Server 2k it's 8000 IIRC). Additionally you will have to take
application level measures to limit the length of inserted values to the
columns width.
Alternatively you could use a TEXT column but changing an existing
VARCHAR to a TEXT column is not as easy as executing an ALTER TABLE.
Kind regards
robert|||Hey Robert,
Thank you for your reply! That's pretty good advice and I think I'll do
just that, since it's far less complicated than what I was trying to do
(obviously).
Robert Klemme wrote:
Quote:
Originally Posted by
On 26.12.2006 12:46, John wrote:
Quote:
Originally Posted by
I have a question about dynamically changing the length of a varchar(n)
field, in case the value I'm trying to insert is too big and will give
a "truncated" error, but before the error is given! i.e. Is there some
kind of a way to "test" the length of the field while Inserting the
value into it, and to have it automatically increase its length to the
length of the value being inserted, in case the value is too big?
I've been able to do this in a "primitive" way, simply by identifying
the specific error number in case the value is being truncated, and
then increasing the length of the varchar(n) field by using the ALTER
command, and then duplicating the insert statement, but is there a
standard (shorter) way of doing this?
>
There are several things to say to this. First, the length of a VARCHAR
column should generally be dependent on business requirements - i.e. the
length comes before the inserted values. You can view it as a
requirement (for example a zip code is just 5 characters here in
Germany) and data not satisfying that requirement basically should not
go into that column. In this case the table will only change if the
business requirement changes (they changed length of zip code from 4 to
5 after the wall broke down over here) and not according to data inserted.
>
Having said that the easiest solution in your case (i.e. if you want to
maintain that you have to insert strings with arbitrary length) is to
just set the length to the max length allowed for that column (in SQL
Server 2k it's 8000 IIRC). Additionally you will have to take
application level measures to limit the length of inserted values to the
columns width.
>
Alternatively you could use a TEXT column but changing an existing
VARCHAR to a TEXT column is not as easy as executing an ALTER TABLE.
>
Kind regards
>
robert
Friday, February 24, 2012
Dynamic table names
how can I generate a temporary table name dynamically? I am selecting
and idnumber from another table. and I need to insert bunch of data to
a #Temptable but it must have that idnumber at the end.
Any ideas?
t.Uh, why not put the id number in a column instead of making it part of the
name?
"tolcis" <nytollydba@.gmail.com> wrote in message
news:1169244127.681152.279510@.a75g2000cwd.googlegroups.com...
> Hi all,
> how can I generate a temporary table name dynamically? I am selecting
> and idnumber from another table. and I need to insert bunch of data to
> a #Temptable but it must have that idnumber at the end.
> Any ideas?
> t.
>
Dynamic table names
how can I generate a temporary table name dynamically? I am selecting
and idnumber from another table. and I need to insert bunch of data to
a #Temptable but it must have that idnumber at the end.
Any ideas?
t.
Uh, why not put the id number in a column instead of making it part of the
name?
"tolcis" <nytollydba@.gmail.com> wrote in message
news:1169244127.681152.279510@.a75g2000cwd.googlegr oups.com...
> Hi all,
> how can I generate a temporary table name dynamically? I am selecting
> and idnumber from another table. and I need to insert bunch of data to
> a #Temptable but it must have that idnumber at the end.
> Any ideas?
> t.
>
Dynamic table names
how can I generate a temporary table name dynamically? I am selecting
and idnumber from another table. and I need to insert bunch of data to
a #Temptable but it must have that idnumber at the end.
Any ideas?
t.Uh, why not put the id number in a column instead of making it part of the
name?
"tolcis" <nytollydba@.gmail.com> wrote in message
news:1169244127.681152.279510@.a75g2000cwd.googlegroups.com...
> Hi all,
> how can I generate a temporary table name dynamically? I am selecting
> and idnumber from another table. and I need to insert bunch of data to
> a #Temptable but it must have that idnumber at the end.
> Any ideas?
> t.
>
Friday, February 17, 2012
dynamic sql performance
select, where, from ... clauses as strings vs normal procedures?
at least i`d think dynamic sql gets compiled on every runPerformance here should not be at the top of your concern list, IMHO.
Please read:
http://www.sommarskog.se/dynamic_sql.html
"Fred" <fred@.ilovespam.com> wrote in message
news:euqdamdJGHA.3896@.TK2MSFTNGP15.phx.gbl...
> i`m wondering how fast r stored procedures which define their insert,
> select, where, from ... clauses as strings vs normal procedures?
> at least i`d think dynamic sql gets compiled on every run|||If you must use dynamic SQL, then build it at the application level and then
submit it via Execute or RowSet.Open. Building long queries or T-SQL within
a stored procedure is clunky.
"Fred" <fred@.ilovespam.com> wrote in message
news:euqdamdJGHA.3896@.TK2MSFTNGP15.phx.gbl...
> i`m wondering how fast r stored procedures which define their insert,
> select, where, from ... clauses as strings vs normal procedures?
> at least i`d think dynamic sql gets compiled on every run|||"JT" <someone@.microsoft.com> wrote in message
news:uvRhNWeJGHA.2696@.TK2MSFTNGP14.phx.gbl...
> If you must use dynamic SQL, then build it at the application level and
> then submit it via Execute or RowSet.Open. Building long queries or T-SQL
> within a stored procedure is clunky.
>
No. All dynamic SQL is somewhat clunky. And TSQL is better for dynamic SQL
than most languages since it allows newlines in literal strings. EG
declare @.sql varchar(8000)
set @.sql = '
select * from
' + @.MyTable + '
where id = 124
and region in (' + @.RegionList + ')
'
Anyway you would just push the clunkyness out into the application. It's
generally simpler and more secure to keep the dynamic SQL close.
David|||Fred wrote:
> i`m wondering how fast r stored procedures which define their insert,
> select, where, from ... clauses as strings vs normal procedures?
> at least i`d think dynamic sql gets compiled on every run
Fast relative to what exactly? If you can do the same thing with static
SQL then you should. You use dynamic code when there is no viable
static alternative.
David Portas, SQL Server MVP
Whenever possible please post enough code to reproduce your problem.
Including CREATE TABLE and INSERT statements usually helps.
State what version of SQL Server you are using and specify the content
of any error messages.
SQL Server Books Online:
http://msdn2.microsoft.com/library/ms130214(en-US,SQL.90).aspx
--|||For the sake of clarity, can you explain further just what
you mean by 'All dynamic SQL is somewhat clunky'.
Terms like 'clunky' can often hide very interesting points of view.
"David Browne" <davidbaxterbrowne no potted meat@.hotmail.com> wrote in
message news:uqD3ZEfJGHA.1088@.tk2msftngp13.phx.gbl...
> "JT" <someone@.microsoft.com> wrote in message
> news:uvRhNWeJGHA.2696@.TK2MSFTNGP14.phx.gbl...
T-SQL
> No. All dynamic SQL is somewhat clunky. And TSQL is better for dynamic
SQL
> than most languages since it allows newlines in literal strings. EG
> declare @.sql varchar(8000)
> set @.sql = '
> select * from
> ' + @.MyTable + '
> where id = 124
> and region in (' + @.RegionList + ')
> '
>
> Anyway you would just push the clunkyness out into the application. It's
> generally simpler and more secure to keep the dynamic SQL close.
> David
>|||RE:
<< Terms like 'clunky' can often hide very interesting points of view.>>
And terms like that frequently hide often very UNinteresting points of view.
It's a form of name-calling. It's like referring to Microsoft as M$... or
that SQL Server is clunky... the CLR is bloat-ware. yadda yadda yadda. Often
these terms are used by luddites
(http://www.google.com/search?hl=en&...ite&btnG=Search).
"05ponyGT" <nospam@.nospam> wrote in message
news:uLHiHcgJGHA.964@.tk2msftngp13.phx.gbl...
> For the sake of clarity, can you explain further just what
> you mean by 'All dynamic SQL is somewhat clunky'.
> Terms like 'clunky' can often hide very interesting points of view.
> "David Browne" <davidbaxterbrowne no potted meat@.hotmail.com> wrote in
> message news:uqD3ZEfJGHA.1088@.tk2msftngp13.phx.gbl...
> T-SQL
> SQL
>|||Thanks for speaking up for Mr. luddite...er Mr. Browne.
I had no idea he was so hostile.
"Smithers" <A@.B.COM> wrote in message
news:OSkddjgJGHA.2912@.tk2msftngp13.phx.gbl...
> RE:
> << Terms like 'clunky' can often hide very interesting points of view.>>
> And terms like that frequently hide often very UNinteresting points of
view.
> It's a form of name-calling. It's like referring to Microsoft as M$... or
> that SQL Server is clunky... the CLR is bloat-ware. yadda yadda yadda.
Often
> these terms are used by luddites
> (http://www.google.com/search?hl=en&...ite&btnG=Search).
>
>
>
> "05ponyGT" <nospam@.nospam> wrote in message
> news:uLHiHcgJGHA.964@.tk2msftngp13.phx.gbl...
and
dynamic
It's
>|||"05ponyGT" <nospam@.nospam> wrote in message
news:uLHiHcgJGHA.964@.tk2msftngp13.phx.gbl...
> For the sake of clarity, can you explain further just what
> you mean by 'All dynamic SQL is somewhat clunky'.
Sure. 'Clunky' was introduced into the thread by JT complaining about
dynamic SQL in stored procedures. I took it to mean that TSQL stored
procedures that use dynamic SQL are not as simple and elegant as stored
procedures which use only static SQL. And dynamic SQL is clunky because you
have two different programs interlaced in one programming unit, where one
program is embedded as a literal string in the other program. That's
clunky.
But it's even more clunky when you embed a SQL program (query) in a 3GL
language like VB or C#. Not only are you building one program as a string
literal in another program, but the programming languages are different, and
the host language often doesn't allow literal strings to span multiple
lines. That's extra clunky.
David|||Please forgive my clunky analysis of the situation.