Monday, March 26, 2012
PRB: Single Query to build database and schema.
Please help, I'm quite frustrated with a problem.
I want to issue a SINGLE query to completely build my database (IF IT
DOESN'T ALREADY EXIST), "use" it, build an entire schema of tables, stored
procedures, triggers, and even populate tables with data.
Envision a typical ASP/ADO using program calling the query as such:
========================================
====
<%@. Language=JavaScript %>
<%
var Connection_Temp;
var ResultSet_Temp;
var csMY_QRY, csOPTION, csMY_DB_NAME;
csMY_QRY = "~~~~~~~ What ever ~~~~~~~~";
csMY_QRY = csMY_QRY.replace("<%=DB%>", csMY_DB_NAME);
csMY_QRY = csMY_QRY.replace("<%=OPTION%>", csOPTION);
.
.
.
Connection_Temp = Server.CreateObject("ADODB.Connection");
Connection_Temp.ConnectionTimeout = 45;
Connection_Temp.Open("DRIVER={SQL
Server};SERVER=My_SVR;UID=MY_UID;PWD=MY_
PWD");
ResultSet_Temp = Connection_Temp.Execute(csMY_QRY);
%>
<html>
</html>
========================================
====
There are several "issues" which are making this very difficult to solve:
1) "CREATE DATABASE" and "USE" do not accept variables.
2) "USE" can not be used in a stored procedure or trigger.
3) sp_executesql only accepts NVARCHAR, NTEXT.
4) NVARCAHR can only be declared up to 4000 bytes.
5) NTEXT data types can only be declared as a parameter, not with "DECLARE".
6) NTEXT defined as parameters can not be assigned with SELECT statements.
7) A typical schema will surely require more than 4000 characters to be
represented
as a string.
8) Even tables with NTEXT can not be fetched into a NTEXT variable such as
this:
create table TEST(JUNK ntext, NAME nvarchar(50) primary key)
insert into TEST(NAME, JUNK) values('ME', 'JUNK')
create procedure TRY(ntext @.csTRY) as
begin
select @.csTRY = JUNK from TEST where NAME = 'ME' -- This fails...
-- Can't assign the NTEXT.
end
9) "GO" can not be used in a stored procedure"
10) "GO" can not be used in a single query passed to ADO as in the above
example.
Put another way, imagine setting csMY_QRY as such:
csMY_QRY = "go \r\n exec sp_help \r\n go exec sp_help";
This will not work in the sample above. SQL Server will say
[Microsoft][ODBC SQL Server Driver][SQL Server]The object 'go' does not
exist in database 'master'.
11) Building the schema MUST be done with transaction handling, so that if
one "CREATE TABLE" fails, they all roll back.
12) THIS HAS TO BE A QUERY.
I am convinced that this can be done. It may require a LOT of sp_executesql
calls, but I feel it can be done.
Any ideas and/or help would be much appreciated.
If nothing else, I would very much like for Microsoft to publish the final
outcome of this PRB as a full blown MSDN article to help everyone. I've
noticed here in the discussion groups that many people are trying to
accomplish this, but are typically getting hung on "CREATE DATABASE" or "USE
"
limitations.I have an update already.
I believe that this WHOLE PRB can be solved if we can do one of the followin
g:
Use some sort of SP to select from a temporary table that has an NTEXT, to
fetch a list of queries, where each query is then executed by something like
sp_executesql, where if ANY failure occurs, the caller will know it, and the
n
be able to roll that query back, and any previous query.
The key is to somehow have an NTEXT variable to get the query, and then pass
it to a sp_executesql as such:
~~~~ somehow DECALRE ~~~~~ @.QRY ntext
select * from QRY_TABLE_WITH_NTEXT_QUERIES
~~~ CURSOR: for each row returned, select into @.QRY ~~~
exec sp_executesql @.QRY
~~~ fetch next - do loop|||Yet another update.
I'm almost there.
The NTEXT is the KEY issue.
If ONLY I could programmatically create and populate an NTEXT variable, WITH
data from a "select * from TABLE_WITH_NTEXT_COLUMN", then I'm sure this PRB
would be solved.
Here is a sample QRY I have made so far. It fails on the FETCH NEXT, where
the error is "[Microsoft][ODBC SQL Server Driver][SQL Server]Cannot fetch
into text, ntext, and image variables. "
===============================
begin transaction
set XACT_ABORT on
set NOCOUNT on
declare @.csQRY nvarchar(4000)
declare @.CrLf nvarchar(5)
declare @.QQ nvarchar(5)
select @.CrLf = char(13) + char(10)
select @.QQ = char(39) + char(39)
select @.csQRY = 'create table QTs([NAME] nvarchar(50), [QRY] ntext)'
exec sp_executesql @.csQRY
select @.csQRY = 'insert into QTs([NAME], [QRY]) values(' + char(39) + 'QRY'
+ char(39) + ', ' + char(39) + 'create database MY_DB' + char(39) + ')'
exec sp_executesql @.csQRY
select @.csQRY = 'insert into QTs([NAME], [QRY]) values(' + char(39) + 'QRY'
+ char(39) + ', ' + char(39) + 'create table MY_DB.dbo.[FUN]([NAME]
nvarchar(50))' + char(39) + ')'
exec sp_executesql @.csQRY
select @.csQRY =
'create procedure DO_QRY(@.QRY ntext = ' + @.QQ + ') as' + @.CrLf +
'begin' + @.CrLf +
' begin transaction' + @.CrLf +
' declare TRY_CURSOR cursor for select [QRY] from QTs' + @.CrLf +
' open TRY_CURSOR' + @.CrLf +
' fetch next from TRY_CURSOR into @.QRY' + @.CrLf +
' while @.@.FETCH_STATUS = 0' + @.CrLf +
' begin' + @.CrLf +
' exec sp_executesql @.QRY' + @.CrLf +
' if (@.@.ERROR <> 0)' + @.CrLf +
' begin' + @.CrLf +
' rollback transaction' + @.CrLf +
' return' + @.CrLf +
' end' + @.CrLf +
' fetch next from TRY_CURSOR into @.QRY' + @.CrLf +
' end' + @.CrLf +
' commit transaction' + @.CrLf +
'end' + @.CrLf
exec sp_executesql @.csQRY
select @.csQRY = 'exec DO_QRY'
exec sp_executesql @.csQRY
commit transaction|||Back to being dead in the water.
I replaced the NTEXT with NVARCHAR(3000), and tried the same login. It
failed on the create database. Now what?
begin transaction
set XACT_ABORT on
set NOCOUNT on
declare @.csQRY nvarchar(4000)
declare @.CrLf nvarchar(5)
declare @.QQ nvarchar(5)
select @.CrLf = char(13) + char(10)
select @.QQ = char(39) + char(39)
select @.csQRY = 'create table QTs([NAME] nvarchar(50), [QRY] nvarchar(3900))'
exec sp_executesql @.csQRY
select @.csQRY = 'insert into QTs([NAME], [QRY]) values(' + char(39) + 'QRY'
+ char(39) + ', ' + char(39) + 'create database MY_DB' + char(39) + ')'
exec sp_executesql @.csQRY
select @.csQRY = 'insert into QTs([NAME], [QRY]) values(' + char(39) + 'QRY'
+ char(39) + ', ' + char(39) + 'create table MY_DB.dbo.[FUN]([NAME]
nvarchar(50))' + char(39) + ')'
exec sp_executesql @.csQRY
select @.csQRY =
'create procedure DO_QRY as' + @.CrLf +
'begin' + @.CrLf +
' begin transaction' + @.CrLf +
' declare @.QRY nvarchar(4000)' + @.CrLf +
' declare TRY_CURSOR cursor for select [QRY] from QTs' + @.CrLf +
' open TRY_CURSOR' + @.CrLf +
' fetch next from TRY_CURSOR into @.QRY' + @.CrLf +
' while @.@.FETCH_STATUS = 0' + @.CrLf +
' begin' + @.CrLf +
' exec sp_executesql @.QRY' + @.CrLf +
' if (@.@.ERROR <> 0)' + @.CrLf +
' begin' + @.CrLf +
' rollback transaction' + @.CrLf +
' return' + @.CrLf +
' end' + @.CrLf +
' fetch next from TRY_CURSOR into @.QRY' + @.CrLf +
' end' + @.CrLf +
' commit transaction' + @.CrLf +
'end' + @.CrLf
exec sp_executesql @.csQRY
select @.csQRY = 'exec DO_QRY'
exec sp_executesql @.csQRY
commit transaction
=================================
In QA, the return is as such:
==================================
Server: Msg 266, Level 16, State 2, Procedure DO_QRY, Line 14
Transaction count after EXECUTE indicates that a COMMIT or ROLLBACK
TRANSACTION statement is missing. Previous count = 1, current count = 0.
Server: Msg 266, Level 16, State 1, Line 1
Transaction count after EXECUTE indicates that a COMMIT or ROLLBACK
TRANSACTION statement is missing. Previous count = 1, current count = 0.
Server: Msg 226, Level 16, State 1, Line 1
CREATE DATABASE statement not allowed within multi-statement transaction.
Server: Msg 3902, Level 16, State 1, Line 38
The COMMIT TRANSACTION request has no corresponding BEGIN TRANSACTION.
===============================
Any ideas?|||SOLVED!!!!!!
The CREATE DATABASE can be issued. I just had to commit any TX that may have
existed before the CREATE DATABASE for it to work. Then I could resume
another "BEGIN TRANSACTION" and continue on. I also needed to use a
WHILE-LOOP to be sure to commit all transactions that may be created by the
various CREATE TABLEs I would execute. But I did get it to work. Final sampl
e
below:
============ This should be published into MSDN, no fooling!
=======================================
begin transaction
set XACT_ABORT on
set NOCOUNT on
declare @.csQRY nvarchar(4000)
declare @.CrLf nvarchar(5)
declare @.QQ nvarchar(5)
select @.CrLf = char(13) + char(10)
select @.QQ = char(39) + char(39)
select @.csQRY = 'create database OptiDoc_3X'
commit transaction
exec sp_executesql @.csQRY
begin transaction
select @.csQRY = 'create table QTs([NAME] nvarchar(50), [QRY] nvarchar(3900))'
exec sp_executesql @.csQRY
--select @.csQRY = 'insert into QTs([NAME], [QRY]) values(' + char(39) +
'QRY' + char(39) + ', ' + char(39) + 'create database MY_DB' + char(39) + ')
'
select @.csQRY = 'insert into QTs([NAME], [QRY]) values(' + char(39) + 'QRY'
+ char(39) + ', ' + char(39) + 'create table MY_DB..MY_TBL([NAME]
nvarchar(50))' + char(39) + ')'
exec sp_executesql @.csQRY
begin transaction
select @.csQRY =
'create procedure DO_QRY as' + @.CrLf +
'begin' + @.CrLf +
' begin transaction' + @.CrLf +
' declare @.QRY nvarchar(4000)' + @.CrLf +
' declare TRY_CURSOR cursor for select [QRY] from QTs' + @.CrLf +
' open TRY_CURSOR' + @.CrLf +
' fetch next from TRY_CURSOR into @.QRY' + @.CrLf +
' while @.@.FETCH_STATUS = 0' + @.CrLf +
' begin' + @.CrLf +
' select @.QRY' + @.CrLf +
' exec sp_executesql @.QRY' + @.CrLf +
' if (@.@.ERROR <> 0)' + @.CrLf +
' begin' + @.CrLf +
' select ' + @.QQ + '-- Error!!!' + @.QQ + @.CrLf +
' rollback transaction' + @.CrLf +
' return' + @.CrLf +
' end' + @.CrLf +
' fetch next from TRY_CURSOR into @.QRY' + @.CrLf +
' end' + @.CrLf +
' close TRY_CURSOR' + @.CrLf +
' deallocate TRY_CURSOR' + @.CrLf +
' commit transaction' + @.CrLf +
'end' + @.CrLf
exec sp_executesql @.csQRY
select @.csQRY = 'exec DO_QRY'
exec sp_executesql @.csQRY
select @.csQRY = 'drop procedure DO_QRY'
exec sp_executesql @.csQRY
select @.csQRY = 'drop table QTs'
exec sp_executesql @.csQRY
while @.@.TRANCOUNT > 0
begin
commit transaction
end
Friday, March 23, 2012
Potential issues with backing up to a network share
What potential issues can you think of or have run into when making
transaction log backups into a single file on a network share. The
MSSQLSERVER service is running under a domain user account, which has
apropriate permissions on the shared folder. The backup is made from a
database in an MS SQL Server 2000 SP3 on an MS Windows Server 2003 SP1 and
the file is stored on an MS Windows 2000 Server SP4.
Many thanks,
OskarIt's slow. If you have a busy OLTP and a large tran file, you can get
memory pressure during the backup. That being said we do it on many of our
servers.
"Oskar" <Oskar@.discussions.microsoft.com> wrote in message
news:ED49A03D-1FBC-42D2-84FA-C7987C0DF005@.microsoft.com...
> Hi
> What potential issues can you think of or have run into when making
> transaction log backups into a single file on a network share. The
> MSSQLSERVER service is running under a domain user account, which has
> apropriate permissions on the shared folder. The backup is made from a
> database in an MS SQL Server 2000 SP3 on an MS Windows Server 2003 SP1 and
> the file is stored on an MS Windows 2000 Server SP4.
> --
> Many thanks,
> Oskar
>sql
Potential issues with backing up to a network share
What potential issues can you think of or have run into when making
transaction log backups into a single file on a network share. The
MSSQLSERVER service is running under a domain user account, which has
apropriate permissions on the shared folder. The backup is made from a
database in an MS SQL Server 2000 SP3 on an MS Windows Server 2003 SP1 and
the file is stored on an MS Windows 2000 Server SP4.
Many thanks,
Oskar
It's slow. If you have a busy OLTP and a large tran file, you can get
memory pressure during the backup. That being said we do it on many of our
servers.
"Oskar" <Oskar@.discussions.microsoft.com> wrote in message
news:ED49A03D-1FBC-42D2-84FA-C7987C0DF005@.microsoft.com...
> Hi
> What potential issues can you think of or have run into when making
> transaction log backups into a single file on a network share. The
> MSSQLSERVER service is running under a domain user account, which has
> apropriate permissions on the shared folder. The backup is made from a
> database in an MS SQL Server 2000 SP3 on an MS Windows Server 2003 SP1 and
> the file is stored on an MS Windows 2000 Server SP4.
> --
> Many thanks,
> Oskar
>
Potential issues with backing up to a network share
What potential issues can you think of or have run into when making
transaction log backups into a single file on a network share. The
MSSQLSERVER service is running under a domain user account, which has
apropriate permissions on the shared folder. The backup is made from a
database in an MS SQL Server 2000 SP3 on an MS Windows Server 2003 SP1 and
the file is stored on an MS Windows 2000 Server SP4.
--
Many thanks,
OskarIt's slow. If you have a busy OLTP and a large tran file, you can get
memory pressure during the backup. That being said we do it on many of our
servers.
"Oskar" <Oskar@.discussions.microsoft.com> wrote in message
news:ED49A03D-1FBC-42D2-84FA-C7987C0DF005@.microsoft.com...
> Hi
> What potential issues can you think of or have run into when making
> transaction log backups into a single file on a network share. The
> MSSQLSERVER service is running under a domain user account, which has
> apropriate permissions on the shared folder. The backup is made from a
> database in an MS SQL Server 2000 SP3 on an MS Windows Server 2003 SP1 and
> the file is stored on an MS Windows 2000 Server SP4.
> --
> Many thanks,
> Oskar
>
Tuesday, March 20, 2012
post from text box to SQL insert
Hello,
I'm trying to update a single field of a record and i want to do it using a standard multi line text box but I'm not sure how to write the c# command to process the sql update. I would also like the entry to be added into the database with line breaks.
Thanks for your help
There is nothing to ask..... you can do it using the same way u r updating the others.... you do not need any c# command.... its the query on which all this depends...
you can use query... : update <table name> set <feild name>= textbox1.text where <condition>....
and about multi lines.... you do not need to worry about line breaks..... the data would be stored in the database just as the way it is in the multiline textbox.... and would be fetched in the same manner...
and do tell me if its any worthy 4 u or not.
|||Ok - In theroy I get what your saying but then I have VisStudio post out the code I need to make the text box and the supporting data source and I get all of this:
----------------
<asp:TextBox ID="txtNotes" runat="server"></asp:TextBox>
<asp:SqlDataSource ID="sqlUpdateNotes" runat="server" ConnectionString="<%$ ConnectionStrings:dbNetOps %>" DeleteCommand="DELETE FROM [MasterServerlist] WHERE [ID] = ?" InsertCommand="INSERT INTO [MasterServerlist] ([ID], [Notes]) VALUES (?, ?)" ProviderName="<%$ ConnectionStrings:dbNetOps.ProviderName %>" SelectCommand="SELECT [ID], [Notes] FROM [MasterServerlist] WHERE ([ID] = ?)" UpdateCommand="UPDATE [MasterServerlist] SET [Notes] = ? WHERE [ID] = ?">
<DeleteParameters>
<asp:Parameter Name="ID" Type="Int32" />
</DeleteParameters>
<UpdateParameters>
<asp:Parameter Name="Notes" Type="String" />
<asp:Parameter Name="ID" Type="Int32" />
</UpdateParameters>
<SelectParameters>
<asp:ControlParameter ControlID="gvServers" Name="ID" PropertyName="SelectedValue"
Type="Int32" />
</SelectParameters>
<InsertParameters>
<asp:Parameter Name="ID" Type="Int32" />
<asp:Parameter Name="Notes" Type="String" />
</InsertParameters>
</asp:SqlDataSource>
------------------
What I'm trying to do is :
1: display the contents of the notes field in the text box where the record matches the record selected in a gridview element
2: have the onchange event of the notes field then post back an update to the database and redisplay the new notes in the text field
I'm very new to ASP and appriciate your help.
Thank you
|||
I cannot find anything wrong in your code... could you please describe your problem in details...... or what kind of errors you are receiving(if any).....
And also you wanted to store all the data in the textbox to the database with the line breaks.... you should set the textmode attribute of textbox to multiline...
Saturday, February 25, 2012
Possible help with query...
Ok, I have a parent table that has a child table, it is a 1-Many relationship. I want to select the single newest child from the child table with the parent table information for each parent value in the table (so if there is a parent record, i only want the newest child record). I have it working, but I am not satisfied with how I have written it. I wanted to see if there were any other opinions on the matter. The way I have it written there *could* be duplicates if somehow the date/time stamps are the same on the created column
here is an example:
DECLARE @.ParentTableTABLE ( ParentIdUNIQUEIDENTIFIER , TitleNVARCHAR(20) )
DECLARE @.ChildTableTABLE ( ChildIdUNIQUEIDENTIFIER , ParentIdUNIQUEIDENTIFIER , TitleNVARCHAR(20) , CreatedDATETIME )INSERT INTO @.ParentTable ( ParentId , Title )VALUES ('00000000-0000-0000-0000-000000000001' ,'Option A' )
INSERT INTO @.ParentTable ( ParentId , Title )VALUES ('00000000-0000-0000-0000-000000000002' ,'Option B' )
INSERT INTO @.ParentTable ( ParentId , Title )VALUES ('00000000-0000-0000-0000-000000000003' ,'Option C' )INSERT INTO @.ChildTable ( ChildId , ParentId , Title , Created )VALUES ('10000000-0000-0000-0000-000000000001' ,'00000000-0000-0000-0000-000000000001' ,'Child A - 1' ,'5/4/2007 4:00:00 PM' )
INSERT INTO @.ChildTable ( ChildId , ParentId , Title , Created )VALUES ('10000000-0000-0000-0000-000000000002' ,'00000000-0000-0000-0000-000000000001' ,'Child A - 2' ,'5/3/2007 4:00:00 PM' )
INSERT INTO @.ChildTable ( ChildId , ParentId , Title , Created )VALUES ('10000000-0000-0000-0000-000000000003' ,'00000000-0000-0000-0000-000000000001' ,'Child A - 3' ,'5/2/2007 4:00:00 PM' )
INSERT INTO @.ChildTable ( ChildId , ParentId , Title , Created )VALUES ('10000000-0000-0000-0000-000000000004' ,'00000000-0000-0000-0000-000000000001' ,'Child A - 4' ,'5/1/2007 4:00:00 PM' )INSERT INTO @.ChildTable ( ChildId , ParentId , Title , Created )VALUES ('20000000-0000-0000-0000-000000000001' ,'00000000-0000-0000-0000-000000000002' ,'Child B - 1' ,'5/1/2007 4:00:00 PM' )
INSERT INTO @.ChildTable ( ChildId , ParentId , Title , Created )VALUES ('20000000-0000-0000-0000-000000000002' ,'00000000-0000-0000-0000-000000000002' ,'Child B - 2' ,'5/10/2007 4:00:00 PM' )
INSERT INTO @.ChildTable ( ChildId , ParentId , Title , Created )VALUES ('20000000-0000-0000-0000-000000000003' ,'00000000-0000-0000-0000-000000000002' ,'Child B - 3' ,'5/2/2007 4:00:00 PM' )INSERT INTO @.ChildTable ( ChildId , ParentId , Title , Created )VALUES ('30000000-0000-0000-0000-000000000001' ,'00000000-0000-0000-0000-000000000003' ,'Child C - 1' ,'5/1/2007 4:00:00 PM' )
INSERT INTO @.ChildTable ( ChildId , ParentId , Title , Created )VALUES ('30000000-0000-0000-0000-000000000002' ,'00000000-0000-0000-0000-000000000003' ,'Child C - 2' ,'5/2/2007 4:00:00 PM' )
INSERT INTO @.ChildTable ( ChildId , ParentId , Title , Created )VALUES ('30000000-0000-0000-0000-000000000003' ,'00000000-0000-0000-0000-000000000003' ,'Child C - 3' ,'5/3/2007 4:00:00 PM' )
INSERT INTO @.ChildTable ( ChildId , ParentId , Title , Created )VALUES ('30000000-0000-0000-0000-000000000004' ,'00000000-0000-0000-0000-000000000003' ,'Child C - 4' ,'5/4/2007 4:00:00 PM' )
INSERT INTO @.ChildTable ( ChildId , ParentId , Title , Created )VALUES ('30000000-0000-0000-0000-000000000005' ,'00000000-0000-0000-0000-000000000003' ,'Child C - 5' ,'5/5/2007 4:00:00 PM' )
INSERT INTO @.ChildTable ( ChildId , ParentId , Title , Created )VALUES ('30000000-0000-0000-0000-000000000006' ,'00000000-0000-0000-0000-000000000003' ,'Child C - 6' ,'5/6/2007 4:00:00 PM' )/**
I want to select the information from the child table and the parent table,
selecting ONLY the oldest record. There should only be 3 results.
**/
SELECT
c.ParentId ,
p.TitleAS ParentTitle ,
c.ChildId ,
c.TitleAS ChildTitle ,
c.Created
FROM
@.ChildTable c
INNERJOIN @.ParentTable pON c.ParentId = p.ParentId
INNERJOIN
(
SELECT
subc.ParentId ,
MAX(subc.Created)AS Created
FROM
@.ChildTable subc
INNERJOIN @.ParentTable subptON subc.ParentId = subpt.ParentId
GROUP BY
subc.ParentId
)AS SubPTON p.ParentId = SubPT.ParentIdAND SubPT.Created = c.Created
here are the expected results:
ParentId ParentTitle ChildId ChildTitle Created
----------- ------- ----------- ------- --------
00000000-0000-0000-0000-000000000001 Option A 10000000-0000-0000-0000-000000000001 Child A - 1 2007-05-04 16:00:00.000
00000000-0000-0000-0000-000000000002 Option B 20000000-0000-0000-0000-000000000002 Child B - 2 2007-05-10 16:00:00.000
00000000-0000-0000-0000-000000000003 Option C 30000000-0000-0000-0000-000000000006 Child C - 6 2007-05-06 16:00:00.000
Anyone have any ideas?
double post ;-(
|||SELECT *FROM (SELECT c.ParentId,p.TitleAS ParentTitle,c.ChildId,c.TitleAS ChildTitle,c.Created,row_number()over(PARTITIONBY c.ParentIDORDER BY CreatedDESC,ChildIDDESC)AS tFROM @.ChildTable cINNERJOIN @.ParentTable pON c.ParentId = p.ParentId) t1WHERE t=1|||
So, I went to try and do this as a learning experiment... I am no SQL Guru or anything, but I thought I was ok. This excersixe showed me I have lots to learn :-)
This is what I came up with, it is probably worse than yours. It is actually more code, and seems a lot worse. But I think I had some creative ideas at least :-)
The following works using 2 extra temp tables ( This is what you are doing in your sub select inner joins, I tried to find a cleaner way, in the end I think your way beat mine)
-- The workItems table actually has the three rows we want, slected from the ordered child table. But I did not know how to join with the groups, and sub queris. So again... I think yours beat mine by a lot, but I am curious what other sorts of results people might come up with.
DECLARE @.orderdChildTableTABLE ( ChildIdUNIQUEIDENTIFIER , ParentIdUNIQUEIDENTIFIER , TitleNVARCHAR(20) , CreatedDATETIME )INSERT INTO @.orderdChildTableSELECT c.ChildId, c.ParentID, c.Title, c.CreatedFROM @.ChildTable cORDER BY c.CreatedDESC|||
DECLARE @.workItemsTABLE (ParentIdUNIQUEIDENTIFIER, CreatedDATETIME)INSERT INTO @.workItemsSelect oct.ParentID,max(oct.Created)From @.orderdChildTable octGROUP BY oct.ParentIDSelect oct.ParentId, p.titleas ParentTitle, oct.ChildId, oct.TitleAS ChildTitle, oct.CreatedFrom @.workItems wiINNERJOIN @.orderdChildTable octON (wi.ParentID = oct.ParentID)AND (wi.Created = oct.Created)LEFTJOIN @.ParentTable pon p.ParentID = wi.ParentIDORDER BY ParentIDASC
Motley, your query certainly looks cleaner than either of ours. (But you do return an extra recordset... which is not really important nor does it bother me).
Can you perhaps elaborate a little, breaking down the query, as to what pieces is doing what. This looks like sql2005 specific stuff, that I am not familiar with. and perhaps others could use a small break down, which helps guide me as to what to read/study up on in my books and google.
I think the piece that I am confused/not familar with is how do I read this statment to understand what exactly it is doing:
row_number
()over(PARTITIONBY c.ParentIDORDERBY CreatedDESC,ChildIDDESC)AS tI am also a little thrown by the double From...
SELECT
*FROM( .... ()AS tFROM @.ChildTable c
INNERJOIN @.ParentTable pON c.ParentId= p.ParentId
) t1
Where t = 1
Im not sure what t1 is either, and what it is supposidly emitting.
|||ah there it is. awesome. i ran into this problem before 2005 and didn't know how to get around it. thanks. i have used the row_number function before, i don't know why i didn't think of it here|||
Motley:
SELECT *
FROM (
SELECT c.ParentId,p.TitleAS ParentTitle,c.ChildId,c.TitleAS ChildTitle,c.Created,row_number()over(PARTITIONBY c.ParentIDORDER BY CreatedDESC,ChildIDDESC)AS t
FROM @.ChildTable c
INNERJOIN @.ParentTable pON c.ParentId = p.ParentId
) t1
WHERE t=1
The query doesn't actually return another recordset, it's a subquery.
Start with:
SELECT c.ParentId,p.TitleAS ParentTitle,c.ChildId,c.TitleAS ChildTitle,c.Created,row_number()over(PARTITIONBY c.ParentIDORDER BY CreatedDESC,ChildIDDESC)AS tFROM @.ChildTable cINNERJOIN @.ParentTable pON c.ParentId = p.ParentIdthe row_number portion of that is telling sqlserver to create a column in the result named "t", and for each row within a "c.ParentID" that is ordered by Created and order by ChildID within that it should represent it's place/rank (It's similiar to rank, but not quite). So the highest Created value for each ParentID will have a value of 1, the second highest is 2, etc etc but when there is a tie with two records of the same ParentID, and Created then it will consider the one with the highest ChildID to be first, basically breaking the tie.
The outer query... SELECT * FROM ( {inner query here} ) t1 WHERE t=1 just says to only take the records where t=1.
t1 is what I am calling the subquery. You always have to give subqueries that are part of the FROM clause an alias.
|||
jminond:
Motley, your query certainly looks cleaner than either of ours. (But you do return an extra recordset... which is not really important nor does it bother me).
Can you perhaps elaborate a little, breaking down the query, as to what pieces is doing what. This looks like sql2005 specific stuff, that I am not familiar with. and perhaps others could use a small break down, which helps guide me as to what to read/study up on in my books and google.
I think the piece that I am confused/not familar with is how do I read this statment to understand what exactly it is doing:
row_number()over(PARTITIONBY c.ParentIDORDERBY CreatedDESC,ChildIDDESC)AS t
I am also a little thrown by the double From...
SELECT*
FROM( .... ()AS tFROM @.ChildTable c
INNERJOIN @.ParentTable pON c.ParentId= p.ParentId
) t1
Where t = 1Im not sure what t1 is either, and what it is supposidly emitting.
The two froms come from the fact you are selecting from the inner result set.
the partition is basically a "grouping" in the rownumber function, it tells the result set to number the results based on the parentid field, thus autonumbering the children 1-X based on the parentid.
t1 refers to the "temporary result set" from the select statement in the ( ), you could also have done "AS t1" to be more direct about what you are doing
and the where t=1 tells the query you only want the results where your temporary identity is 1, thus the newest child row for each parent row
if any of that makes sense
possible bug regarding single line comments in SQL Server Management Studio
I don't know if this is a bug or something I've messed up in my settings. I am using SQL Server Management Studio with SQL 2005 service pack 1 installed, and I've been using it successfully ever since SP1 came out. All of a sudden, any time I have a query with a single line comment (i.e. using dash dash -- ), the rest of the query is ignored as if the single line comment is really a multi-line comment without the closing */
An example:
select top 100 *
from myTable
-- this is a comment
where myTableID = 1234
This would normally return exactly one row, but instead returns 100 rows ( as if the where clause did not exist). If I move the where clause above the comment, it works as expected. Any ideas?
In trying to fix this, I've uninstalled and reinstalled and even reinstalled SP1, but it still isn't fixed.
You've got me stumped. I took the code you have posted and it ran fine for me.
Can you post the exact code that you are using? Maybe we'll see that hanging character you missed or somthing.
|||I used the exact query, merely changing the table name and ID column.
I ended up going through the process yet again (uninstalling the tools, reinstalling the tools, then installing SP1) and rebooted but still had the problem. However, after a second reboot, it starting behaving properly again. I hope my problem does not resurface.
|||We (me a colleague of mine), have withnessed this same behaviour and, atfer some deep analysis, we have concluded that this bug arises when the Transact-Sql line terminates with a CR (Carriage Return, Ascii(13)) only charaters when it should terminate with both CR (Carriage Return, Ascii(13)) followed by an LF (Line Feed, Ascii(10))It seems that once SqlServer reachs a single-line comment identifier (--) it keeps fetching bytes untill a compounded line termination (CR followed by LF) is reached.
In the following sample, the {CR+LF} and {CR} are representations of their respective invisible ascii codes.
--This is just a normal single-line comment {CR+LF}
SELECT 'This command works fine' {CR+LF}
--This is a buggy single-line comment {CR}
SELECT 'This command does not work'{CR}
SELECT 'This command does not work either' {CR+LF}
SELECT 'This command work fine too' {CR+LF}
Moreover we have reasons to bellieve that this bug resides in Query Editor provided with SQL Server Management Studio Express Edition (at least, this was version my colleague was using when this bug arose). Anyway, although this bug must be corrected, LF should just be ignored when dealing with Sql scripts.
Running software:
SQL Server Management Studio Express Edition
Ms SQLServer 2000 (8.0.2039)
Getting this sample you can:
- Load and execute it, using QueryAnalyzer to see the refered behaviour;
- View it, using Notepad, to see what actually happened.
possible bug regarding single line comments in SQL Server Management Studio
I don't know if this is a bug or something I've messed up in my settings. I am using SQL Server Management Studio with SQL 2005 service pack 1 installed, and I've been using it successfully ever since SP1 came out. All of a sudden, any time I have a query with a single line comment (i.e. using dash dash -- ), the rest of the query is ignored as if the single line comment is really a multi-line comment without the closing */
An example:
select top 100 *
from myTable
-- this is a comment
where myTableID = 1234
This would normally return exactly one row, but instead returns 100 rows ( as if the where clause did not exist). If I move the where clause above the comment, it works as expected. Any ideas?
In trying to fix this, I've uninstalled and reinstalled and even reinstalled SP1, but it still isn't fixed.
You've got me stumped. I took the code you have posted and it ran fine for me.
Can you post the exact code that you are using? Maybe we'll see that hanging character you missed or somthing.
|||I used the exact query, merely changing the table name and ID column.
I ended up going through the process yet again (uninstalling the tools, reinstalling the tools, then installing SP1) and rebooted but still had the problem. However, after a second reboot, it starting behaving properly again. I hope my problem does not resurface.
|||We (me a colleague of mine), have withnessed this same behaviour and, atfer some deep analysis, we have concluded that this bug arises when the Transact-Sql line terminates with a CR (Carriage Return, Ascii(13)) only charaters when it should terminate with both CR (Carriage Return, Ascii(13)) followed by an LF (Line Feed, Ascii(10))It seems that once SqlServer reachs a single-line comment identifier (--) it keeps fetching bytes untill a compounded line termination (CR followed by LF) is reached.
In the following sample, the {CR+LF} and {CR} are representations of their respective invisible ascii codes.
--This is just a normal single-line comment {CR+LF}
SELECT 'This command works fine' {CR+LF}
--This is a buggy single-line comment {CR}
SELECT 'This command does not work'{CR}
SELECT 'This command does not work either' {CR+LF}
SELECT 'This command work fine too' {CR+LF}
Moreover we have reasons to bellieve that this bug resides in Query Editor provided with SQL Server Management Studio Express Edition (at least, this was version my colleague was using when this bug arose). Anyway, although this bug must be corrected, LF should just be ignored when dealing with Sql scripts.
Running software:
SQL Server Management Studio Express Edition
Ms SQLServer 2000 (8.0.2039)
Getting this sample you can:
- Load and execute it, using QueryAnalyzer to see the refered behaviour;
- View it, using Notepad, to see what actually happened.