Showing posts with label file. Show all posts
Showing posts with label file. Show all posts

Tuesday, March 27, 2012

Collation Order

How can I change the collation order for a msde db?
With SQL Server I use Rebuildm.exe utility, but with msde
that file is not present.
thanks,
AF
If your release doesnt contain a rebuildm.exe i am afraid that you will
have to setup Sql Server once again, or perhaps get a copy from one of your
non-MSDE SQL Servers (
HTH, Jens Suessmeyer.
http://www.sqlserver2005.de
<anonymous@.discussions.microsoft.com> schrieb im Newsbeitrag
news:0bcd01c54689$47bdc490$a401280a@.phx.gbl...
> How can I change the collation order for a msde db?
> With SQL Server I use Rebuildm.exe utility, but with msde
> that file is not present.
> thanks,
> AF
|||hi,
anonymous@.discussions.microsoft.com wrote:
> How can I change the collation order for a msde db?
> With SQL Server I use Rebuildm.exe utility, but with msde
> that file is not present.
> thanks,
> AF
yes, MSDE distributions do not include rebuildm.exe, but you can specify
alternate collation(s) for users' databases.. .. you can incur in some
overhead where different collations are involved in tempdb (as tempdb
inherits system collation), but this scenario is supported...
else you have to uninstall and reinstall MSDE with the desired collation
specifying the
COLLATION="selected_collation"
parameter at install time to the setup.exe boostrap installer (
http://msdn.microsoft.com/library/en...stsql_84xl.asp )
Andrea Montanari (Microsoft MVP - SQL Server)
http://www.asql.biz/DbaMgr.shtmhttp://italy.mvps.org
DbaMgr2k ver 0.11.1 - DbaMgr ver 0.57.0
(my vb6+sql-dmo little try to provide MS MSDE 1.0 and MSDE 2000 a visual
interface)
-- remove DMO to reply
sqlsql

Thursday, March 8, 2012

Code formatting for SQL2005 TSQL

Hi !
I have a monster case statement in TSL, autogenerated with some external
program I do not have access to.
The source file is about 4K in size, and the resulting source code probably
will have a few hunderd lines of code if formatted properly for reading.
Is there a feature in SQL 2005 management studio for code formatting ? BIDS
then ?
If not, a reccommendation for a tool for code formatting, preferably free,
would be greatly appreciated.
Regards,
Palli
"Pall Bjornsson" <palli@.kvos.is> wrote in message
news:ejv5S05nHHA.1388@.TK2MSFTNGP05.phx.gbl...
> Hi !
> I have a monster case statement in TSL, autogenerated with some external
> program I do not have access to.
> The source file is about 4K in size, and the resulting source code
> probably will have a few hunderd lines of code if formatted properly for
> reading.
> Is there a feature in SQL 2005 management studio for code formatting ?
> BIDS then ?
> If not, a reccommendation for a tool for code formatting, preferably free,
> would be greatly appreciated.
> Regards,
> Palli
Like this?
http://www.simple-talk.com/sql/sql-tools/the-simple-talk-sql-prettifier/
|||>
> Like this?
> http://www.simple-talk.com/sql/sql-tools/the-simple-talk-sql-prettifier/
>
Thanks for the link!
It does half the job, but not quite. It gets confused when 5 or 6 case
statement's END appear in a row!
Any other free options ?
Palli
|||"Pall Bjornsson" <palli@.kvos.is> wrote in message
news:ealOwM8nHHA.4424@.TK2MSFTNGP03.phx.gbl...
> Thanks for the link!
> It does half the job, but not quite. It gets confused when 5 or 6 case
> statement's END appear in a row!
> Any other free options ?
> Palli
If you report that as a possible bug to the author, I imagine he'll jump in
and try to fix it. I don't really know of any other free options myself. I
have heard about some old VB6 trick to access some undocumented feature of a
system DLL to format SQL/T-SQL Code. Not sure where the info is located for
this trick exactly, or if it would even work for SQL 2005, but you might be
able to Google something on it. The problem is that generally a custom code
prettifier for a language as complex as SQL/T-SQL would require you to
implement an LALR parser and a complete SQL/T-SQL grammar from scratch, or a
very deep (read: "slow") recursive-descent parser. For most people it's
probably just a lot easier to prettify their code by hand or just pay for a
pre-built package.
|||Try http://www.sqlinform.com/ and
http://www.wangz.net/gsqlparser/sqlpp/sqlformat.htm
TheSQLGuru
President
Indicium Resources, Inc.
"Pall Bjornsson" <palli@.kvos.is> wrote in message
news:ealOwM8nHHA.4424@.TK2MSFTNGP03.phx.gbl...
> Thanks for the link!
> It does half the job, but not quite. It gets confused when 5 or 6 case
> statement's END appear in a row!
> Any other free options ?
> Palli
>
|||Now that link is too cool I've heard of the GSP, but didn't realize
someone had set up a Web Service to use it.
"TheSQLGuru" <kgboles@.earthlink.net> wrote in message
news:OHbsgqYoHHA.1388@.TK2MSFTNGP05.phx.gbl...
> Try http://www.sqlinform.com/ and
> http://www.wangz.net/gsqlparser/sqlpp/sqlformat.htm
> --
> TheSQLGuru
> President
> Indicium Resources, Inc.
> "Pall Bjornsson" <palli@.kvos.is> wrote in message
> news:ealOwM8nHHA.4424@.TK2MSFTNGP03.phx.gbl...
>
|||> Try http://www.sqlinform.com/ and
> http://www.wangz.net/gsqlparser/sqlpp/sqlformat.htm
>
This is really cool... both of those tools. Thanks a lot.
Palli
|||"Pall Bjornsson" <palli@.kvos.is> wrote in message
news:uWen8lpoHHA.3460@.TK2MSFTNGP04.phx.gbl...
> This is really cool... both of those tools. Thanks a lot.
> Palli
BTW, Phil Factor (the author of the one I sent you) has updated his code.
He also has the source code for the T-SQL stored procedure available for
download. Not sure if it fixes the bug you pointed out, but it might.

code creating a flat file destination

I'm looking for a manner to create by code a flat file connection manager and a flat file destination.GreetsTry the last post in this thread -http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=359347&SiteID=1|||Thanks!

Wednesday, March 7, 2012

Code Access Security in SQL Server 2000 Reporting Services

I have a 3rd party DLL that I need to give Full Trust to. Here is the code in
the prvpolicy.config file I am using to do so. My question is, what am I
doing wrong?
Does it need a certain name or is the <IMembershipCondition
class="UrlMembershipCondition" the wrong thing or?
<CodeGroup class="UnionCodeGroup"
version="1"
PermissionSetName="FullTrust"
Name="AzaleaBarcode"
Description="Code group for processing azalea font barcodes">
<IMembershipCondition class="UrlMembershipCondition"
version="1"
Url="C:\Program Files\Azalea\Bar Code Engine\Barcode.dll"
/>
</CodeGroup>We're working on the same exact problem. Has anyone solved this problem?
"Pinolian" <Pinolian@.discussions.microsoft.com> wrote in message news:<B8247CA5-44C0-4E59-BE3D-EABDFC22EEE1@.microsoft.com>...
> I have a 3rd party DLL that I need to give Full Trust to. Here is the code in
> the prvpolicy.config file I am using to do so. My question is, what am I
> doing wrong?
> Does it need a certain name or is the <IMembershipCondition
> class="UrlMembershipCondition" the wrong thing or?
>
> <CodeGroup class="UnionCodeGroup"
> version="1"
> PermissionSetName="FullTrust"
> Name="AzaleaBarcode"
> Description="Code group for processing azalea font barcodes">
> <IMembershipCondition class="UrlMembershipCondition"
> version="1"
> Url="C:\Program Files\Azalea\Bar Code Engine\Barcode.dll"
> />
> </CodeGroup>

COBOL program output "text" file for SQL Server to read?

Hello
When a COBOL program outputs a "text" file how can SQL Server read that text
file?winlin,
You can import it a number of ways. Read about BCP or BULK INSERT and its
format files. I am assuming that you will need to give some instruction via
the format file about how to parse the "text" file.
Or you may insert it into a staging table with a format something like:
CREATE TABLE CobolStaging
(LineOfCobolText NVARCHAR(1000))
Further, I am assuming that every line is in the same format, so that it can
be viewed as a row in a table. But if that is not the case, then the
reading in is more complex since it would probably be row order dependent
how to interpret the data. (E.g. header rows and detail rows. In that
case, use a table like:
CREATE TABLE CobolStaging
(LineNum INT IDENTITY(1,1)
LineOfCobolText NVARCHAR(1000))
You will need a format file to teach it to skip over the LineNum column when
importing.
After you have read and experimented with BCP you will probably have some
new questions.
RLF
"winlin" <winlin@.verizon.com> wrote in message
news:40E16360-C774-43A6-B4A9-B1B7B5FC4F2B@.microsoft.com...
> Hello
> When a COBOL program outputs a "text" file how can SQL Server read that
> text
> file?

Saturday, February 25, 2012

cmdsql - Create a text file without Informational Messages

Hello all

I have a sql file that I want execute by using the cmdsql command line. But when I create a text file I receive two Informational Messages:

1."Changed database context to 'DataBaseName'."

2.(2 row(s) affected)

How can I ignore these messages in my text file? there is a parametter or something elese to configure to avoir these Informational Messages?

Sorry is not cmdsql is Sqlcmd :)

CmdExec issue

Hello,
I have a batch file in the operating system, which runs an osql command that
create a stored procedure, a view and a function on a database. It is with
-E trust connect. It works when I just run it on windows.
However, if I run in as a SQL Job by using the CmdExec, it could not create
any stored procedure, view or function. And there is no error return
neither. The account to run the job is the same NT account with local admin
rights on the server.
Does anyone have some idea about this matter?
Many Thanks,
LianneAre you running the Job from a different server?
If so you need to use -U and -P providing a username and password. I
have experienced this problem before, but apparently linked servers do
not pass the user via windows authentication.|||Lianne Kwock (LianneKwock@.discussions.microsoft.com) writes:
> I have a batch file in the operating system, which runs an osql command
> that create a stored procedure, a view and a function on a database. It
> is with -E trust connect. It works when I just run it on windows.
> However, if I run in as a SQL Job by using the CmdExec, it could not
> create any stored procedure, view or function. And there is no error
> return neither. The account to run the job is the same NT account with
> local admin rights on the server.
Did the job fail or succeed?
In case it failed, there is a checkbox in the upper right of the View
History dialog which says "Show job steps" or somesuch. The output from
the job step should have the real error.
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|||The job was running on the physical server. and the job return as
successful. but nothing was created on SQL Server side.
Thanks again,
Lianne
"Johnny D" wrote:

> Are you running the Job from a different server?
> If so you need to use -U and -P providing a username and password. I
> have experienced this problem before, but apparently linked servers do
> not pass the user via windows authentication.
>|||Hi John,
I change the -E to -U sa login, but I got this error message:
Login failed for user 'sa'. Reason: Not associated with a trusted SQL Server
connection.
Any idea?
Many Thanks,
Lianne
"Johnny D" wrote:

> Are you running the Job from a different server?
> If so you need to use -U and -P providing a username and password. I
> have experienced this problem before, but apparently linked servers do
> not pass the user via windows authentication.
>|||Xref: TK2MSFTNGP01.phx.gbl microsoft.public.sqlserver.programming:605603
Lianne Kwock (LianneKwock@.discussions.microsoft.com) writes:
> I change the -E to -U sa login, but I got this error message:
> Login failed for user 'sa'. Reason: Not associated with a trusted SQL
> Server connection.
> Any idea?
That would indicate that SQL authentication is not enabled on the server.
Well, changing the autentication should not matter, so consider that a
dead end.
As for why your job does not work as expected, I'm afraid that with the
information you have provided, all we can offer is wild guesses. What
is the exact command line you are using?
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|||Hi Eriand,
the command line is below:
for %%f IN (*.sql) DO echo %%f >> Createcp.txt & osql -S LKWOCK-D1 -U sa -P
zhongshan -n -d test -i "%%f" >> Createcp.txt
this is the command I put in .bat file. on the same level, I have three sql
files, which creates a view, a user defined function and a stored procedure.
Also, I had set SQL Server running on both (SQL and NT authentication)
If you meed more informations, let me know.
Many Thanks,
Lianne
"Erland Sommarskog" wrote:

> Lianne Kwock (LianneKwock@.discussions.microsoft.com) writes:
> That would indicate that SQL authentication is not enabled on the server.
> Well, changing the autentication should not matter, so consider that a
> dead end.
> As for why your job does not work as expected, I'm afraid that with the
> information you have provided, all we can offer is wild guesses. What
> is the exact command line you are using?
>
> --
> 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
>|||Lianne Kwock (LianneKwock@.discussions.microsoft.com) writes:
> the command line is below:
> for %%f IN (*.sql) DO echo %%f >> Createcp.txt & osql -S LKWOCK-D1 -U
> sa -P zhongshan -n -d test -i "%%f" >> Createcp.txt
> this is the command I put in .bat file. on the same level, I have three
> sql files, which creates a view, a user defined function and a stored
> procedure.
Real stupid question: the BAT file does include a CD to the directory
where you have the SQL, doesn't it?
I composed this file on my machine:
F:
cd \moje dokumenty\WWW\dynsearch
for %%f IN (*.sp) DO echo %%f >> Createcp.txt & osql -E -n -d Northgale -i "
%%f" >> Createcp.txt
And the I created a job of which the command text was
C:\temp\test.bat
I deleted all stored procedure in Northgale, and then started the job.
When I had completed the job, all my procedures were back.
In job history I saw this for the job step:
Executed as user: KESMETS\sql. ...search
F:\Moje dokumenty\WWW\dynsearch>for %f IN (*.sp) DO echo %f 1>>Createcp.tx
t & osql -E -n -d Northgale -i "%f" 1>>Createcp.txt
F:\Moje dokumenty\WWW\dynsearch>echo search_orders_1.sp 1>>Createcp.txt &
osql -E -n -d Northgale -i "search_orders_1.sp" 1>>Createcp.txt
F:\Moje dokumenty\WWW\dynsearch>echo search_orders_10.sp 1>>Createcp.txt
& osql -E -n -d Northgale -i "search_orders_10.sp" 1>>Createcp.txt
F:\Moje dokumenty\WWW\dynsearch>echo search_orders_2.sp 1>>Createcp.txt &
osql -E -n -d Northgale -i "search_orders_2.sp" 1>>Createcp.txt
F:\Moje dokumenty\WWW\dynsearch>echo search_orders_3.sp 1>>Createcp.txt &
osql -E -n -d Northgale -i "search_orders_3.sp" 1>>Createcp.txt
F:\Moje dokumenty\WWW\dynsearch>echo search_orders_3a.sp 1>>Createcp.txt
& osql -E -n -d Northgale -i "search_orders_3a.sp" 1>>Createcp.txt
F:\Moje dokumenty\WWW\dynsearch>echo search_orders_4.sp 1>>Createcp.txt &
.. Process Exit Code 0. The step succeeded.
A way to get more output from the job step is to go the Advanced tab
for the job step, and there select a output file.
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|||Hi Erland,
Thank you very much for your suggection. I did not enclude the Cd line in
the .bat file since it work just fine when I run it through windows. My bad
.
I guess SQL is very piggy on directory specification then.
Thank you again. I appreciate your help very much!
Lianne
"Erland Sommarskog" wrote:

> Lianne Kwock (LianneKwock@.discussions.microsoft.com) writes:
> Real stupid question: the BAT file does include a CD to the directory
> where you have the SQL, doesn't it?
> I composed this file on my machine:
> F:
> cd \moje dokumenty\WWW\dynsearch
> for %%f IN (*.sp) DO echo %%f >> Createcp.txt & osql -E -n -d Northgale
-i "%%f" >> Createcp.txt
> And the I created a job of which the command text was
> C:\temp\test.bat
> I deleted all stored procedure in Northgale, and then started the job.
> When I had completed the job, all my procedures were back.
> In job history I saw this for the job step:
>
> Executed as user: KES?METS?\sql. ...search
> F:\Moje dokumenty\WWW\dynsearch>for %f IN (*.sp) DO echo %f 1>>Create
cp.txt & osql -E -n -d Northgale -i "%f" 1>>Createcp.txt
> F:\Moje dokumenty\WWW\dynsearch>echo search_orders_1.sp 1>>Createcp.t
xt & osql -E -n -d Northgale -i "search_orders_1.sp" 1>>Createcp.txt
> F:\Moje dokumenty\WWW\dynsearch>echo search_orders_10.sp 1>>Createcp.
txt & osql -E -n -d Northgale -i "search_orders_10.sp" 1>>Createcp.txt
> F:\Moje dokumenty\WWW\dynsearch>echo search_orders_2.sp 1>>Createcp.t
xt & osql -E -n -d Northgale -i "search_orders_2.sp" 1>>Createcp.txt
> F:\Moje dokumenty\WWW\dynsearch>echo search_orders_3.sp 1>>Createcp.t
xt & osql -E -n -d Northgale -i "search_orders_3.sp" 1>>Createcp.txt
> F:\Moje dokumenty\WWW\dynsearch>echo search_orders_3a.sp 1>>Createcp.
txt & osql -E -n -d Northgale -i "search_orders_3a.sp" 1>>Createcp.txt
> F:\Moje dokumenty\WWW\dynsearch>echo search_orders_4.sp 1>>Createcp.t
xt &... Process Exit Code 0. The step succeeded.
> A way to get more output from the job step is to go the Advanced tab
> for the job step, and there select a output file.
>
> --
> 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
>

CmdExec in a Nightly Job

I have to verify a .CSV file exists before I run a BULK INSERT. I am using XP_FileExist in SQL 2000 to accomplish this. After the Bulk Insert is completed and validated, I need to Rename the file and Move the file to archive the folder. For testing I figure If I can rename the file I can move it. I suspect I have permission issues and need to provide the SQL Server Agent permissions to this folder and file. I have my PC setup as a SQL 2000 Server and am attempting to get this step only working on my local machine. I created a nightly Job that remanes a file that I created in a Job and that is all it does. I am running the Job as SA but am still having issues.

The step being executed by the Job is "Ren C:\MyTestFile.csv C:\MyTestFile1.csv" (with the quotes). If I run this statment (without the Quotes from a command prompt, the file is renamed.

I have set the Type as "Operating System Command (CmdEXEC)". The Job history shows "The process could not be created for step 2 of job 0x71D51027F920A140A2913234DB7FF509 (reason: The system cannot find the file specified). The step failed."

As I said, I suspect that it is a permissions issue as the command works from the command prompt. What is the windows account that the SQL Server Agent uses to commit these commands? I added "Everyone" with Full access to the folder and I still get the same failure.

I would appreciate any assistance anyone could provide. Thanks in advance!

SQL Server Agent has its own service account -it doesn't use the 'sa' account.

In Enterprise Manager, right-click on SQL Agent, then Properties, and you can view (and/or change) the service account for the SQL Server Agent service.

Here are a couple of resources about setting the SQL Agent account:

Configuration -Service Accounts, SQL Server 2005 - Setting Up Windows Service Accounts
http://msdn2.microsoft.com/en-us/library/ms143691.aspx
http://msdn2.microsoft.com/en-us/library/ms143504.aspx

Configuration -Service Accounts, SQL Server or SQL Server Agent service account
http://support.microsoft.com/kb/283811/en-us
http://msdn2.microsoft.com/en-us/library/ms143691.aspx

Configuration -Service Accounts,Selecting an Account for the SQL Server Agent Service
http://msdn2.microsoft.com/en-us/library/ms191543.aspx
http://support.microsoft.com/kb/907557

CMDEXEC Can't Find File, Yet Runs In a "Run" Dialog

Good morning, I hope someone here has had this problem and can tell me what
I'm doing wrong.
I have created a CMDEXEC job to run a program. I know my path is correct
because it works in a Run dialog. Yet SQL Server Agent reports "Process
could not be created... the system cannot find the file specified" in the
error log.
The job step is currently set to the path and name of the exe. I.e.:
\\server\folder\app.exe
Agent reports "Success" for this step after just a second, but the
application runs for an hour or so when it's started manually. Even if the
application was failing and crashing out, which it does not do when run
manually, it should take it a few seconds. Is Agent starting the app in the
background, asynchronously?
Any suggestions appreciated!JonOfAllTrades wrote:
> Good morning, I hope someone here has had this problem and can tell me wha
t
> I'm doing wrong.
> I have created a CMDEXEC job to run a program. I know my path is correct
> because it works in a Run dialog. Yet SQL Server Agent reports "Process
> could not be created... the system cannot find the file specified" in the
> error log.
> The job step is currently set to the path and name of the exe. I.e.:
> \\server\folder\app.exe
> Agent reports "Success" for this step after just a second, but the
> application runs for an hour or so when it's started manually. Even if th
e
> application was failing and crashing out, which it does not do when run
> manually, it should take it a few seconds. Is Agent starting the app in t
he
> background, asynchronously?
> Any suggestions appreciated!
It's a permissions problem. SQL Agent is running as a user (or maybe
Local System) that doesn't have permission to access
\\server\folder\app.exe. Fix that, and all should be well.
Tracy McKibben
MCDBA
http://www.realsqlguy.com

CMDEXEC Can't Find File, Yet Runs In a "Run" Dialog

Good morning, I hope someone here has had this problem and can tell me what
I'm doing wrong.
I have created a CMDEXEC job to run a program. I know my path is correct
because it works in a Run dialog. Yet SQL Server Agent reports "Process
could not be created... the system cannot find the file specified" in the
error log.
The job step is currently set to the path and name of the exe. I.e.:
\\server\folder\app.exe
Agent reports "Success" for this step after just a second, but the
application runs for an hour or so when it's started manually. Even if the
application was failing and crashing out, which it does not do when run
manually, it should take it a few seconds. Is Agent starting the app in the
background, asynchronously?
Any suggestions appreciated!JonOfAllTrades wrote:
> Good morning, I hope someone here has had this problem and can tell me what
> I'm doing wrong.
> I have created a CMDEXEC job to run a program. I know my path is correct
> because it works in a Run dialog. Yet SQL Server Agent reports "Process
> could not be created... the system cannot find the file specified" in the
> error log.
> The job step is currently set to the path and name of the exe. I.e.:
> \\server\folder\app.exe
> Agent reports "Success" for this step after just a second, but the
> application runs for an hour or so when it's started manually. Even if the
> application was failing and crashing out, which it does not do when run
> manually, it should take it a few seconds. Is Agent starting the app in the
> background, asynchronously?
> Any suggestions appreciated!
It's a permissions problem. SQL Agent is running as a user (or maybe
Local System) that doesn't have permission to access
\\server\folder\app.exe. Fix that, and all should be well.
Tracy McKibben
MCDBA
http://www.realsqlguy.com

cmd.ExecuteNonQuery question..help please

I have a DataAccess that has "cmd.ExecuteNonQuery" and another file SqlTableProfileProvider for a SandBox project(from ASP.NET) for a Custom TableProfileProvider. That also has a cmd.ExecuteNonQuery even thou these are 2 different files i get an error after debug.

Question is are they conflicting ? if so how can i fix this.

Code Snippets for both provided below the 2nd cmd.ExecuteNonQuery that is producing the Error is Commented in Orange...Thxs for the help Rattlerr

Incorrect syntax near ','.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Data.SqlClient.SqlException: Incorrect syntax near ','.

Source Error:

Line 454: cmd.CommandType = CommandType.Text; Line 455: Line 456: cmd.ExecuteNonQuery(); Line 457: Line 458: // Need to close reader before we try to update

[SqlException (0x80131904): Incorrect syntax near ','.]
System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection) +859322
System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection) +736198
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj) +188
System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) +1959
System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString) +149
System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async) +903
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result) +132
System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(DbAsyncResult result, String methodName, Boolean sendToPipe) +415
System.Data.SqlClient.SqlCommand.ExecuteNonQuery() +135
Microsoft.Samples.SqlTableProfileProvider.SetPropertyValues(SettingsContext context, SettingsPropertyValueCollection collection) in d:\Programming Programs\Xtremesystems\Xtremesystems\xs\App_Code\SqlTableProfileProvider.cs:456
System.Configuration.SettingsBase.SaveCore() +379
System.Configuration.SettingsBase.Save() +77
System.Web.Profile.ProfileBase.SaveWithAssert() +31
System.Web.Profile.ProfileBase.Save() +63
System.Web.Profile.ProfileModule.OnLeave(Object source, EventArgs eventArgs) +2374047
System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +92
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +64

DataAccess.cs::

Code Snippet

public abstract class DataAccess

{

private string _connectionString = "";

protected string ConnectionString

{

get { return _connectionString; }

set { _connectionString = value; }

}

private bool _enableCaching = true;

protected bool EnableCaching

{

get { return _enableCaching; }

set { _enableCaching = value; }

}

private int _cacheDuration = 0;

protected int CacheDuration

{

get { return _cacheDuration; }

set { _cacheDuration = value; }

}

protected Cache Cache

{

get { return HttpContext.Current.Cache; }

}

protected int ExecuteNonQuery(DbCommand cmd)

{

if (HttpContext.Current.User.Identity.Name.ToLower() == "sampleeditor")

{

foreach (DbParameter param in cmd.Parameters)

{

if (param.Direction == ParameterDirection.Output ||

param.Direction == ParameterDirection.ReturnValue)

{

switch (param.DbType)

{

case DbType.AnsiString:

case DbType.AnsiStringFixedLength:

case DbType.String:

case DbType.StringFixedLength:

case DbType.Xml:

param.Value = "";

break;

case DbType.Boolean:

param.Value = false;

break;

case DbType.Byte:

param.Value = byte.MinValue;

break;

case DbType.Date:

case DbType.DateTime:

param.Value = DateTime.MinValue;

break;

case DbType.Currency:

case DbType.Decimal:

param.Value = decimal.MinValue;

break;

case DbType.Guid:

param.Value = Guid.Empty;

break;

case DbType.Double:

case DbType.Int16:

case DbType.Int32:

case DbType.Int64:

param.Value = 0;

break;

default:

param.Value = null;

break;

}

}

}

return 1;

}

else

return cmd.ExecuteNonQuery();

}

protected IDataReader ExecuteReader(DbCommand cmd)

{

return ExecuteReader(cmd, CommandBehavior.Default);

}

protected IDataReader ExecuteReader(DbCommand cmd, CommandBehavior behavior)

{

return cmd.ExecuteReader(behavior);

}

protected object ExecuteScalar(DbCommand cmd)

{

return cmd.ExecuteScalar();

}

SecondFile::

Code Snippet

public override void SetPropertyValues(SettingsContext context, SettingsPropertyValueCollection collection) {

string username = (string)context["UserName"];

bool userIsAuthenticated = (bool)context["IsAuthenticated"];

if (username == null || username.Length < 1 || collection.Count < 1)

return;

SqlConnection conn = null;

SqlDataReader reader = null;

SqlCommand cmd = null;

try {

bool anyItemsToSave = false;

// First make sure we have at least one item to save

foreach (SettingsPropertyValue pp in collection) {

if (pp.IsDirty) {

if (!userIsAuthenticated) {

bool allowAnonymous = (bool)pp.Property.Attributes["AllowAnonymous"];

if (!allowAnonymous)

continue;

}

anyItemsToSave = true;

break;

}

}

if (!anyItemsToSave)

return;

conn = new SqlConnection(_sqlConnectionString);

conn.Open();

List<ProfileColumnData> columnData = new List<ProfileColumnData>(collection.Count);

foreach (SettingsPropertyValue pp in collection) {

if (!userIsAuthenticated) {

bool allowAnonymous = (bool)pp.Property.Attributes["AllowAnonymous"];

if (!allowAnonymous)

continue;

}

//Normal logic for original SQL provider

//if (!pp.IsDirty && pp.UsingDefaultValue) // Not fetched from DB and not written to

//Can eliminate unnecessary updates since we are using a table though

if (!pp.IsDirty)

continue;

string persistenceData = pp.Property.Attributes["CustomProviderData"] as string;

// If we can't find the table/column info we will ignore this data

if (String.IsNullOrEmpty(persistenceData)) {

// REVIEW: Perhaps we should throw instead?

continue;

}

string[] chunk = persistenceData.Split(new char[] { ';' });

if (chunk.Length != 2) {

// REVIEW: Perhaps we should throw instead?

continue;

}

string columnName = chunk[0];

// REVIEW: Should we ignore case?

SqlDbType datatype = (SqlDbType)Enum.Parse(typeof(SqlDbType), chunk[1], true);

object value = null;

// REVIEW: Is this handling null case correctly?

if (pp.Deserialized && pp.PropertyValue == null) { // is value null?

value = DBNull.Value;

}

else {

value = pp.PropertyValue;

}

// REVIEW: Might be able to ditch datatype

columnData.Add(new ProfileColumnData(columnName, pp, value, datatype));

}

// Figure out userid, if we don't find a userid, go ahead and create a user in the aspnetUsers table

Guid userId = Guid.Empty;

cmd = new SqlCommand("SELECT u.UserId FROM vw_aspnet_Users u WHERE u.ApplicationId = '" + AppId + "' AND u.UserName = LOWER(@.Username)", conn);

cmd.CommandType = CommandType.Text;

cmd.Parameters.AddWithValue("@.Username",username);

try {

reader = cmd.ExecuteReader();

if (reader.Read()) {

userId = reader.GetGuid(0);

}

else {

reader.Close();

cmd.Dispose();

reader = null;

cmd = new SqlCommand("dbo.aspnet_Users_CreateUser", conn);

cmd.CommandType = CommandType.StoredProcedure;

cmd.Parameters.AddWithValue("@.ApplicationId", AppId);

cmd.Parameters.AddWithValue("@.UserName", username);

cmd.Parameters.AddWithValue("@.IsUserAnonymous", !userIsAuthenticated);

cmd.Parameters.AddWithValue("@.LastActivityDate", DateTime.UtcNow);

cmd.Parameters.Add(CreateOutputParam("@.UserId", SqlDbType.UniqueIdentifier, 16));

cmd.ExecuteNonQuery();

userId = (Guid)cmd.Parameters["@.userid"].Value;

}

}

finally {

if (reader != null) {

reader.Close();

reader = null;

}

cmd.Dispose();

}

// Figure out if the row already exists in the table and use appropriate SELECT/UPDATE

cmd = new SqlCommand(String.Empty, conn);

StringBuilder sqlCommand = new StringBuilder("IF EXISTS (SELECT 1 FROM ").Append(_table);

sqlCommand.Append(" WHERE UserId = @.UserId) ");

cmd.Parameters.AddWithValue("@.UserId", userId);

// Build up strings used in the query

StringBuilder columnStr = new StringBuilder();

StringBuilder valueStr = new StringBuilder();

StringBuilder setStr = new StringBuilder();

int count = 0;

foreach (ProfileColumnData data in columnData) {

columnStr.Append(", ");

valueStr.Append(", ");

columnStr.Append(data.ColumnName);

string valueParam = "@.Value" + count;

valueStr.Append(valueParam);

cmd.Parameters.AddWithValue(valueParam, data.Value);

// REVIEW: Can't update Timestamps?

if (data.DataType != SqlDbType.Timestamp) {

if (count > 0) {

setStr.Append(",");

}

setStr.Append(data.ColumnName);

setStr.Append("=");

setStr.Append(valueParam);

}

++count;

}

columnStr.Append(",LastUpdatedDate ");

valueStr.Append(",@.LastUpdatedDate");

setStr.Append(",LastUpdatedDate=@.LastUpdatedDate");

cmd.Parameters.AddWithValue("@.LastUpdatedDate", DateTime.UtcNow);

sqlCommand.Append("BEGIN UPDATE ").Append(_table).Append(" SET ").Append(setStr.ToString());

sqlCommand.Append(" WHERE UserId = '").Append(userId).Append("'");

sqlCommand.Append("END ELSE BEGIN INSERT ").Append(_table).Append(" (UserId").Append(columnStr.ToString());

sqlCommand.Append(") VALUES ('").Append(userId).Append("'").Append(valueStr.ToString()).Append(") END");

cmd.CommandText = sqlCommand.ToString();

cmd.CommandType = CommandType.Text;

cmd.ExecuteNonQuery(); //THIS cmd.ExecuteNonQuery Produces the Error

// Need to close reader before we try to update

if (reader != null) {

reader.Close();

reader = null;

}

UpdateLastActivityDate(conn, userId);

}

finally {

if (reader != null)

reader.Close();

if (cmd != null)

cmd.Dispose();

if (conn != null)

conn.Close();

}

}

YOu have a syntax error in your code, please post the CommandText of the Execution before the actual command is executed. With this command we can see what is wrong with your TSQL code.

Jens K. Suessmeyer.

http://www.sqlserver2005.de
|||

I suggest that immediately before the cmd.ExecuteNonQuery() statement, that perhaps it would be useful to add a messagebox.show, and display your command. Obviously, there is a syntax error and it needs to be examined.

If the error is not obvious to you, post it here and perhaps we can help.

|||

I posted the Code but its not showing up in here ..lol but anyways here is the Modified version where i put in a Try ,Catch block..I also tried the MessageBox like you mentioned but it tells me the same thing as every other method..

But here is the Preceding Code::

Code Snippet

public class SqlTableProfileProvider : ProfileProvider {

private string _appName;

private Guid _appId;

private bool _appIdSet;

private string _sqlConnectionString;

private int _commandTimeout;

private string _table;

public override void Initialize(string name, NameValueCollection config) {

if (config == null)

throw new ArgumentNullException("config");

if (String.IsNullOrEmpty(name))

name = "SqlTableProfileProvider";

if (string.IsNullOrEmpty(config["description"])) {

config.Remove("description");

config.Add("description", "SqlTableProfileProvider");

}

base.Initialize(name, config);

string temp = config["connectionStringName"];

if (String.IsNullOrEmpty(temp))

throw new ProviderException("connectionStringName not specified");

_sqlConnectionString = SqlStoredProcedureProfileProvider.GetConnectionString(temp);

if (String.IsNullOrEmpty(_sqlConnectionString)) {

throw new ProviderException("connectionStringName not specified");

}

_appName = config["applicationName"];

if (string.IsNullOrEmpty(_appName))

_appName = SqlStoredProcedureProfileProvider.GetDefaultAppName();

if (_appName.Length > 256) {

throw new ProviderException("Application name too long");

}

_table = config["table"];

if (string.IsNullOrEmpty(_table)) {

throw new ProviderException("No table specified");

}

EnsureValidTableOrColumnName(_table);

string timeout = config["commandTimeout"];

if (string.IsNullOrEmpty(timeout) || !Int32.TryParse(timeout, out _commandTimeout)) {

_commandTimeout = 30;

}

config.Remove("commandTimeout");

config.Remove("connectionStringName");

config.Remove("applicationName");

config.Remove("table");

if (config.Count > 0) {

string attribUnrecognized = config.GetKey(0);

if (!String.IsNullOrEmpty(attribUnrecognized))

throw new ProviderException("Unrecognized config attribute:" + attribUnrecognized);

}

}

public override string ApplicationName {

get { return _appName; }

set {

if (value == null)

throw new ArgumentNullException("ApplicationName");

if (value.Length > 256) {

throw new ProviderException("Application name too long");

}

_appName = value;

_appIdSet = false;

}

}

private Guid AppId {

get {

if (!_appIdSet) {

SqlConnection conn = null;

try {

conn = new SqlConnection(_sqlConnectionString);

conn.Open();

SqlCommand cmd = new SqlCommand("dbo.aspnet_Applications_CreateApplication", conn);

cmd.CommandType = CommandType.StoredProcedure;

cmd.Parameters.AddWithValue("@.applicationname", ApplicationName);

cmd.Parameters.Add(CreateOutputParam("@.ApplicationId", SqlDbType.UniqueIdentifier, 0));

cmd.ExecuteNonQuery();

_appId = (Guid)cmd.Parameters["@.ApplicationId"].Value;

_appIdSet = true;

}

finally {

if (conn != null) {

conn.Close();

}

}

}

return _appId;

}

}

private int CommandTimeout {

get { return _commandTimeout; }

}

////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////

private static string s_legalChars = "_@.#$";

private static void EnsureValidTableOrColumnName(string name) {

for (int i = 0; i < name.Length; ++i) {

if (!Char.IsLetterOrDigit(name[i]) && s_legalChars.IndexOf(name[i]) == -1)

throw new ProviderException("Table and column names cannot contain: "+name[i]);

}

}

private void GetProfileDataFromTable(SettingsPropertyCollection properties, SettingsPropertyValueCollection svc, string username, SqlConnection conn) {

List<ProfileColumnData> columnData = new List<ProfileColumnData>(properties.Count);

StringBuilder commandText = new StringBuilder("SELECT u.UserID");

SqlCommand cmd = new SqlCommand(String.Empty, conn);

int columnCount = 0;

foreach (SettingsProperty prop in properties) {

SettingsPropertyValue value = new SettingsPropertyValue(prop);

svc.Add(value);

string persistenceData = prop.Attributes["CustomProviderData"] as string;

// If we can't find the table/column info we will ignore this data

if (String.IsNullOrEmpty(persistenceData)) {

// REVIEW: Perhaps we should throw instead?

continue;

}

string[] chunk = persistenceData.Split(new char[] { ';' });

if (chunk.Length != 2) {

// REVIEW: Perhaps we should throw instead?

continue;

}

string columnName = chunk[0];

// REVIEW: Should we ignore case?

SqlDbType datatype = (SqlDbType)Enum.Parse(typeof(SqlDbType), chunk[1], true);

columnData.Add(new ProfileColumnData(columnName, value, null /* not needed for get */, datatype));

commandText.Append(", ");

commandText.Append("t."+columnName);

++columnCount;

}

commandText.Append(" FROM "+_table+" t, vw_aspnet_Users u WHERE u.ApplicationId = '").Append(AppId);

commandText.Append("' AND u.UserName = LOWER(@.Username) AND t.UserID = u.UserID");

cmd.CommandText = commandText.ToString();

cmd.CommandType = CommandType.Text;

cmd.Parameters.AddWithValue("@.Username", username);

SqlDataReader reader = null;

try {

reader = cmd.ExecuteReader();

//If no row exists in the database, then the default Profile values

//from configuration are used.

if (reader.Read()) {

Guid userId = reader.GetGuid(0);

for (int i = 0; i < columnData.Count; ++i) {

object val = reader.GetValue(i+1);

ProfileColumnData colData = columnData[i];

SettingsPropertyValue propValue = colData.PropertyValue;

//Only initialize a SettingsPropertyValue for non-null values

if (!(val is DBNull || val == null))

{

propValue.PropertyValue = val;

propValue.IsDirty = false;

propValue.Deserialized = true;

}

}

// need to close reader before we try to update the user

if (reader != null) {

reader.Close();

reader = null;

}

UpdateLastActivityDate(conn, userId);

}

}

finally {

if (reader != null) {

reader.Close();

}

}

}

private static void UpdateLastActivityDate(SqlConnection conn, Guid userId) {

SqlCommand cmd = new SqlCommand("UPDATE aspnet_Users SET LastActivityDate = @.LastUpdatedDate WHERE UserId = '" + userId + "'", conn);

cmd.CommandType = CommandType.Text;

cmd.Parameters.AddWithValue("@.LastUpdatedDate", DateTime.UtcNow);

try {

cmd.ExecuteNonQuery();

}

finally {

cmd.Dispose();

}

}

public override SettingsPropertyValueCollection GetPropertyValues(SettingsContext context, SettingsPropertyCollection collection) {

SettingsPropertyValueCollection svc = new SettingsPropertyValueCollection();

if (collection == null || collection.Count < 1 || context == null)

return svc;

string username = (string)context["UserName"];

if (String.IsNullOrEmpty(username))

return svc;

SqlConnection conn = null;

try {

conn = new SqlConnection(_sqlConnectionString);

conn.Open();

GetProfileDataFromTable(collection, svc, username, conn);

}

finally {

if (conn != null) {

conn.Close();

}

}

return svc;

}

////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////

// Container struct for use in aggregating columns for queries

private struct ProfileColumnData {

public string ColumnName;

public SettingsPropertyValue PropertyValue;

public object Value;

public SqlDbType DataType;

public ProfileColumnData(string col, SettingsPropertyValue pv, object val, SqlDbType type) {

EnsureValidTableOrColumnName(col);

ColumnName = col;

PropertyValue = pv;

Value = val;

DataType = type;

}

}

Here i put in a Try & Catch block but it tells me nothing new, i even tried your Method of the MessageBox before the cmd.ExecuteNonQuery but it tells me nothing new

either..Tells me the same error as in my 1st post..

MessageBox.Show(cmd.ExecuteNonQuery().ToString());

|||

Comment out the

cmd.ExecuteNonQuery

line, and add

Messagebox.show ( SQLCommand ).

You need to 'SEE' the command in order to see and correct the syntax problem!

|||

Error 102 'System.Data.SqlClient.SqlCommand' is a 'type' but is used like a 'variable'

The following line produces the error above..

MessageBox.Show(SqlCommand);

//cmd.ExecuteNonQuery();

|||

My regrets, I thought you would understand that we need to see the contents of the command string in the command object -in this situation, the variable 'cmd'.

SqlCommand cmd = new SqlCommand("UPDATE aspnet_Users SET LastActivityDate = @.LastUpdatedDate WHERE UserId = '" + userId + "'", conn);

|||

Sorry for any confusion but this is what i put cause it wouldnt let me define a new cmd in the current scope, so i put this in their.I'm kinda frustrated on this so, If this isn't what you need to see please show me what i need to put in their..

This also has to do with my post in the T-Sql Section for the sample Schema script for creating the ProfileTable_1 ( http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=1536893&SiteID=1). That you helped me with Arnie where i put::

grant EXECUTE on dbo.aspnet_Applications_CreateApplication to [WYATT-PC\Wyatt]

It will run the script saying "Query Executed Successfully" but it also says::

Cannot grant, deny, or revoke permissions to sa, dbo, entity owner, information_schema, sys, or yourself.

Thxs Rattlerr

MessageBox.Show(cmd.CommandText.ToString() );

But this is the Results of the MessageBox::

IF EXISTS (SELECT 1 FROM ProfileTable_1 WHERE UserId = @.UserId) BEGIN

UPDATE ProfileTable_1 SET, LastUpdatedDate = @.LastUpdatedDate WHERE UserId =

long encrypted string ' END ELSE BEGIN INSERT

ProfileTable_1 (UserId, LastUpdatedDate) VALUES

('Another encrypted string', @.LastUpdatedDate) END

Schema Script related to my post in the T-Sql Area link is provided above::

Code Snippet

--

--Set this to the name of your database

--

use xtremesystems

go

--

--grants on ASP.NET stored procedures and tables used by the custom providers

--

grant EXECUTE on dbo.aspnet_Applications_CreateApplication to [WYATT-PC\Wyatt]

grant EXECUTE on dbo.aspnet_Users_CreateUser to [WYATT-PC\Wyatt]

grant SELECT on dbo.aspnet_Users to [WYATT-PC\Wyatt]

grant UPDATE on dbo.aspnet_Users(LastActivityDate) to [WYATT-PC\Wyatt]

go

--drop table dbo.ProfileTable_1

--go

create table dbo.ProfileTable_1 (

UserId uniqueidentifier not null Primary Key,

FirstName nvarchar(50) null,

LastName nvarchar(50) null,

Age int null,

LastUpdatedDate datetime not null)

go

grant SELECT,INSERT,UPDATE,DELETE on dbo.ProfileTable_1 to [WYATT-PC\Wyatt]

go

--

--Get stored procedure

--

--drop procedure getCustomProfileData

create procedure getCustomProfileData

@.ApplicationName nvarchar(256),

@.UserName nvarchar(256),

@.FirstName nvarchar(50) OUTPUT,

@.LastName nvarchar(50) OUTPUT,

@.Age int OUTPUT

as

declare @.ApplicationId uniqueidentifier

set @.ApplicationId = NULL

--Get the appid

exec dbo.aspnet_Applications_CreateApplication @.ApplicationName, @.ApplicationId OUTPUT

--Return data for the requested user in the application

select @.FirstName = FirstName,

@.LastName = LastName,

@.Age = Age

from dbo.ProfileTable_1 pt,

dbo.vw_aspnet_Users u

where u.ApplicationId = @.ApplicationId

and u.UserName = @.UserName

and u.UserId = pt.UserId

go

grant EXECUTE on dbo.getCustomProfileData to [WYATT-PC\Wyatt]

go

--

--Set stored procedure

--

--drop procedure setCustomProfileData

create procedure setCustomProfileData

@.ApplicationName nvarchar(256),

@.UserName nvarchar(256),

@.IsUserAnonymous bit,

@.FirstName nvarchar(50),

@.LastName nvarchar(50),

@.Age int

as

declare @.ApplicationId uniqueidentifier

set @.ApplicationId = NULL

declare @.CurrentUtcDate datetime

set @.CurrentUtcDate = getutcdate()

--Get the appid

exec dbo.aspnet_Applications_CreateApplication @.ApplicationName, @.ApplicationId OUTPUT

--Create user if needed

declare @.UserId uniqueidentifier

select @.UserId = UserId

from dbo.vw_aspnet_Users

where ApplicationId = @.ApplicationId

and LoweredUserName = LOWER(@.UserName)

if(@.UserId IS NULL)

exec dbo.aspnet_Users_CreateUser @.ApplicationId, @.UserName, @.IsUserAnonymous, @.CurrentUtcDate, @.UserId OUTPUT

--Either insert a new row of data, or update a pre-existing row

if exists (select 1 from dbo.ProfileTable_1 where UserId = @.UserId)

BEGIN

update dbo.ProfileTable_1

set FirstName = @.FirstName,

LastName = @.LastName,

Age = @.Age,

LastUpdatedDate = @.CurrentUtcDate

where UserId = @.UserId

END

else

BEGIN

insert dbo.ProfileTable_1 (UserId, FirstName, LastName, Age, LastUpdatedDate)

values (@.UserId, @.FirstName, @.LastName, @.Age, @.CurrentUtcDate)

END

go

grant EXECUTE on dbo.setCustomProfileData to [WYATT-PC\Wyatt]

go

|||

Rattlerr wrote:

grant EXECUTE on dbo.aspnet_Applications_CreateApplication to [WYATT-PC\Wyatt]

It will run the script saying "Query Executed Successfully" but it also says::

Cannot grant, deny, or revoke permissions to sa, dbo, entity owner, information_schema, sys, or yourself.

Yes, that is correct. You cannot GRANT permissions to yourself. If I recall correctly, you wanted to GRANT permission to ASPNET and you were having difficulty with the value used for [YOURMACHINENAME]. 'Somehow' it was coming up as 'WYATT-PC\Wyatt' rather than just 'WYATT-PC'.

I have take the liberty to reformat the code below so that it is more readible...



IF EXISTS (SELECT 1 FROM ProfileTable_1 WHERE UserId = @.UserId)
BEGIN
UPDATE ProfileTable_1
SET, LastUpdatedDate = @.LastUpdatedDate
WHERE UserId =long encrypted string '
END
ELSE
BEGIN
INSERTProfileTable_1 (UserId, LastUpdatedDate)
VALUES ('Another encrypted string', @.LastUpdatedDate)
END

It appears that when you are putting the query together, there are a couple of errors.


1. In the [yellow] section, there is a unneeded comma that causes a syntax error.
2. In the ]green] section, the is a missing quote after the equals sign and before the string value.
3. In the [blue] section, there 'should' be a space between INSERT and ProfileTable_1

Correct these errors and let us know if you are still experiencing the same problems -or, as I suspect, other problems will show up.

|||

lol sorry i put long encyrpted string in their cause it was a long encrypted string and alot to type out..But i will type it all out this is what shows up in the MessageBox::

IF EXISTS (SELECT 1 FROM ProfileTable_1 WHERE userId = @.UserId)

BEGIN

UPDATE ProfileTable_1

SET, LastUpdatedDate = @.LastUpdatedDate

WHERE UserId = 'cf76b1dc-691f-4987-8b2b-579d21bbcab'

END

BEGIN

INSERT ProfileTable_1 (UserId, LastUpdatedDate)

VALUES ('cf76b1dc-691f-4987-8b2b-579d21bbcab', @.LastUpdatedDate)

END

Here is the section of the script that matchs that MessageBox..

Code Snippet

private static void UpdateLastActivityDate(SqlConnection conn, Guid userId) {

SqlCommand cmd = new SqlCommand("UPDATE aspnet_Users SET LastActivityDate = @.LastUpdatedDate WHERE UserId = '" + userId + "'", conn);

cmd.CommandType = CommandType.Text;

cmd.Parameters.AddWithValue("@.LastUpdatedDate", DateTime.UtcNow);

try {

cmd.ExecuteNonQuery();

}

finally {

cmd.Dispose();

}

}

& This Section:

Code Snippet

// Figure out if the row already exists in the table and use appropriate SELECT/UPDATE

cmd = new SqlCommand(String.Empty, conn);

StringBuilder sqlCommand = new StringBuilder("IF EXISTS (SELECT 1 FROM ").Append(_table);

sqlCommand.Append(" WHERE UserId = @.UserId) ");

cmd.Parameters.AddWithValue("@.UserId", userId);

// Build up strings used in the query

StringBuilder columnStr = new StringBuilder();

StringBuilder valueStr = new StringBuilder();

StringBuilder setStr = new StringBuilder();

int count = 0;

foreach (ProfileColumnData data in columnData)

{

columnStr.Append(", ");

valueStr.Append(", ");

columnStr.Append(data.ColumnName);

string valueParam = "@.Value" + count;

valueStr.Append(valueParam);

cmd.Parameters.AddWithValue(valueParam, data.Value);

// REVIEW: Can't update Timestamps?

if (data.DataType != SqlDbType.Timestamp)

{

if (count > 0)

{

setStr.Append(",");

}

setStr.Append(data.ColumnName);

setStr.Append("=");

setStr.Append(valueParam);

}

++count;

}

columnStr.Append(",LastUpdatedDate ");

valueStr.Append(",@.LastUpdatedDate");

setStr.Append(",LastUpdatedDate=@.LastUpdatedDate");

cmd.Parameters.AddWithValue("@.LastUpdatedDate", DateTime.UtcNow);

sqlCommand.Append("BEGIN UPDATE ").Append(_table).Append(" SET ").Append(setStr.ToString());

sqlCommand.Append(" WHERE UserId = '").Append(userId).Append("'");

sqlCommand.Append("END ELSE BEGIN INSERT ").Append(_table).Append(" (UserId").Append(columnStr.ToString());

sqlCommand.Append(") VALUES ('").Append(userId).Append("'").Append(valueStr.ToString()).Append(") END");

cmd.CommandText = sqlCommand.ToString();

cmd.CommandType = CommandType.Text;

try

{

MessageBox.Show(cmd.CommandText.ToString() );

//cmd.ExecuteNonQuery();

Testing it now I removed the comma from in front of the setStr.Append(",LastUpdatedDate=@.LastUpdatedDate"); see what happens now..

|||

By removing the comma where i mentioned in my last post the Syntax Error has gone away, but know i have a new error thats being caught by the try ,catch block .. Any idea's on this one?

Would i be correct to assume that has something to do with the Stored Procedures?

And again Thxs for all the help and being patient with me..lol Cheers

Must declare the scalar varible "@.Value1LastUpdatedDate".

Code Snippet

--

--Set stored procedure

--

--drop procedure setCustomProfileData

ALTER procedure setCustomProfileData

@.ApplicationName nvarchar(256),

@.UserName nvarchar(256),

@.IsUserAnonymous bit,

@.FirstName nvarchar(50),

@.LastName nvarchar(50),

@.Age int

as

declare @.ApplicationId uniqueidentifier

set @.ApplicationId = NULL

declare @.CurrentUtcDate datetime

set @.CurrentUtcDate = getutcdate()

--Get the appid

exec dbo.aspnet_Applications_CreateApplication @.ApplicationName, @.ApplicationId OUTPUT

--Create user if needed

declare @.UserId uniqueidentifier

select @.UserId = UserId

from dbo.vw_aspnet_Users

where ApplicationId = @.ApplicationId

and LoweredUserName = LOWER(@.UserName)

if(@.UserId IS NULL)

exec dbo.aspnet_Users_CreateUser @.ApplicationId, @.UserName, @.IsUserAnonymous, @.CurrentUtcDate, @.UserId OUTPUT

--Either insert a new row of data, or update a pre-existing row

if exists (select 1 from dbo.ProfileTable_1 where UserId = @.UserId)

BEGIN

update dbo.ProfileTable_1

set FirstName = @.FirstName,

LastName = @.LastName,

Age = @.Age,

LastUpdatedDate = @.CurrentUtcDate

where UserId = @.UserId

END

else

BEGIN

insert dbo.ProfileTable_1 (UserId, FirstName, LastName, Age, LastUpdatedDate)

values (@.UserId, @.FirstName, @.LastName, @.Age, @.CurrentUtcDate)

END

Thats related to this section of code::

Code Snippet

StringBuilder columnStr = new StringBuilder();

StringBuilder valueStr = new StringBuilder();

StringBuilder setStr = new StringBuilder();

int count = 0;

foreach (ProfileColumnData data in columnData)

{

columnStr.Append(", ");

valueStr.Append(", ");

columnStr.Append(data.ColumnName);

string valueParam = "@.Value" + count;

valueStr.Append(valueParam);

cmd.Parameters.AddWithValue(valueParam, data.Value);

// REVIEW: Can't update Timestamps?

if (data.DataType != SqlDbType.Timestamp)

{

if (count > 0)

{

setStr.Append(",");

}

setStr.Append(data.ColumnName);

setStr.Append("=");

setStr.Append(valueParam);

}

++count;

}

columnStr.Append(",LastUpdatedDate ");

valueStr.Append(",@.LastUpdatedDate");

//Removed Comma from infront of the LastUpdatedDate=@.LastUpdatedDate

setStr.Append("LastUpdatedDate=@.LastUpdatedDate");

cmd.Parameters.AddWithValue("@.LastUpdatedDate", DateTime.UtcNow);

sqlCommand.Append("BEGIN UPDATE ").Append(_table).Append(" SET ").Append(setStr.ToString());

sqlCommand.Append(" WHERE UserId = '").Append(userId).Append("'");

sqlCommand.Append("END ELSE BEGIN INSERT ").Append(_table).Append(" (UserId").Append(columnStr.ToString());

sqlCommand.Append(") VALUES ('").Append(userId).Append("'").Append(valueStr.ToString()).Append(") END");

cmd.CommandText = sqlCommand.ToString();

cmd.CommandType = CommandType.Text;

try

{

cmd.ExecuteNonQuery();

//MessageBox.Show(cmd.Parameters.ToString());

|||

This is my last attempt to help you. It appears that in your attempt to create separate stringbuilder objects for columnstr, setstr, and valuestr, you may have created a level of complexity that is apparently beyound your competence.

It is not clear if you are using a stored procedure or a query string. You have presented both.

The error has NOTHING to do with the included stored procedure, and everything to do with how you have lost sight of creating your query string.

If you would ONLY take some positive actions to find out what is in the query string, such as my suggestion to use a messagebox.show to display the query string for view, you would be helping yourself. You're wasting a lot of your time (as well as ours) by not using your tools to give you information to help yourself.

If you did so, you would see that your latest error

Must declare the scalar varible "@.Value1LastUpdatedDate".

is most likely because the variable '@.Value1' is being concatenated to the field name 'LastUpdatedDate' without a space and/or comma between.

Check out how you are handling 'valueParam' in the stringbuilder objects.

I hate to come on so 'strongly', but, come on, you have to start using your head and your tools.

|||

I appreciate the help but again in my posts " I did not write that code" it was a SandBox project from the site Asp.net. I'm only trying to get it to work while " learning" something in the process.

http://www.asp.net/sandbox/samp_profiles.aspx?tabid=62

Like your comment says:: Most good judgment comes from experience. Most experience comes from bad judgment. - Anonymous

People like myself don't have all the experience as others have thats why its a learning process and some like myself A: cant afford schooling and buy books when the money is aviable. So remember you wasn't born with the knowledge for programming you learned it over time, so cut me some slack

|||

I've suggested repeatedly:

Comment out the ExecuteNoQuery statement, Add a MessageBox.Show statement to display the entire Query String You will then be able to 'see' the Query, and you can help yourself -instead of repeatedly asking for others to read through all this code for you.|||Another simpler way to debug this is turn on SQL Profiler on the server side and it will show you the incoming SQL statement along with the error reported (potentially pointing to the line of tsql that is in error).

Friday, February 10, 2012

Clustered index and file space question

I have been doing testing on tables sizes and I ran into a
situation that I do not understand.
My default fill factor is set to 95%.
I used a SELECT INTO to copy a fact table for testing.
The table was about 1.1 GB in size.
I then created a primary key /clustered index on an
integer value on the new table.
The table grew to about 1.9 GB in size.
I then truncated this table but left the index on it.
I then ran an INSERT INTO statement to copy the origianl
fact table.
The table was 1.1 GB in size and contained the clustered
index.
Why would creating a clustered index increase a table's
size when inserting into a table with an existing
clustered index had no significant size difference?
Doesn't the clustered index actually contain the data
pages and therefore shouldn't affect the size of the table?
Thanks,
Jonathan Lacefield
MCDBAThis is a multi-part message in MIME format.
--=_NextPart_000_01F7_01C376C4.E95D4FA0
Content-Type: text/plain;
charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable
When you create or rebuild a clustered index, SQL Server requires 1.2 X =the size of the table in free space in order to do the sort.
-- Tom
---
Thomas A. Moreau, BSc, PhD, MCSE, MCDBA
SQL Server MVP
Columnist, SQL Server Professional
Toronto, ON Canada
www.pinnaclepublishing.com/sql
"Jonathan Lacefield" <Jonathan.lacefield@.solutionbuilders.com> wrote in =message news:002c01c376e5$98532500$a301280a@.phx.gbl...
I have been doing testing on tables sizes and I ran into a situation that I do not understand.
My default fill factor is set to 95%.
I used a SELECT INTO to copy a fact table for testing. The table was about 1.1 GB in size.
I then created a primary key /clustered index on an integer value on the new table. The table grew to about 1.9 GB in size.
I then truncated this table but left the index on it. I then ran an INSERT INTO statement to copy the origianl fact table.
The table was 1.1 GB in size and contained the clustered index.
Why would creating a clustered index increase a table's size when inserting into a table with an existing clustered index had no significant size difference? Doesn't the clustered index actually contain the data pages and therefore shouldn't affect the size of the table?
Thanks,
Jonathan Lacefield
MCDBA
--=_NextPart_000_01F7_01C376C4.E95D4FA0
Content-Type: text/html;
charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
&

When you create or rebuild a clustered =index, SQL Server requires 1.2 X the size of the table in free space in order to do =the sort.
-- Tom
---T=homas A. Moreau, BSc, PhD, MCSE, MCDBASQL Server MVPColumnist, SQL =Server ProfessionalToronto, ON Canadahttp://www.pinnaclepublishing.com/sql">www.pinnaclepublishing.com=/sql
"Jonathan Lacefield" wrote in message news:002c01c376e5$98=532500$a301280a@.phx.gbl...I have been doing testing on tables sizes and I ran into a situation =that I do not understand.My default fill factor is set to 95%.I =used a SELECT INTO to copy a fact table for testing. The table was =about 1.1 GB in size.I then created a primary key /clustered index on an integer value on the new table. The table grew to about =1.9 GB in size.I then truncated this table but left the index on it. =I then ran an INSERT INTO statement to copy the origianl fact =table.The table was 1.1 GB in size and contained the clustered =index.Why would creating a clustered index increase a table's size when inserting =into a table with an existing clustered index had no significant size difference? Doesn't the clustered index actually contain the =data pages and therefore shouldn't affect the size of the table?Thanks,Jonathan LacefieldMCDBA

--=_NextPart_000_01F7_01C376C4.E95D4FA0--|||This is a multi-part message in MIME format.
--=_NextPart_000_0025_01C37769.7486AB40
Content-Type: text/plain;
charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable
Tibor, I don't believe that the space is released after the rebuild. =Let's say you had a single-file filegroups with only one 100MB, =non-indexed table in it. If you created a clustered index on it, I'd =expect the file to be about 220MB when completed. This happens to me =when I rebuild large tables. I see it in my file growth and the free =space available in the file.
-- Tom
----
Thomas A. Moreau, BSc, PhD, MCSE, MCDBA
SQL Server MVP
Columnist, SQL Server Professional
Toronto, ON Canada
www.pinnaclepublishing.com/sql
.
"Tibor Karaszi" =<tibor.please_reply_to_public_forum.karaszi@.cornerstone.se> wrote in =message news:%23G$gqX4dDHA.2804@.TK2MSFTNGP11.phx.gbl...
... but that should be released after the rebuild is done. The question =is, I guess, how Jonathan checked the space used (file or table level)? =If at table level, how was that done (sysindexes was up-to-date or not)? =Also, assuming that able level and correct info, what did DBCC =SHOWCONTIG say (avg page density)?
-- Tibor Karaszi, SQL Server MVP
Archive at: http://groups.google.com/groups?oi=3Ddjq&as =ugroup=3Dmicrosoft.public.sqlserver
"Tom Moreau" <tom@.dont.spam.me.cips.ca> wrote in message =news:uw9AgZudDHA.3464@.TK2MSFTNGP11.phx.gbl...
When you create or rebuild a clustered index, SQL Server requires 1.2 =X the size of the table in free space in order to do the sort.
-- Tom
---
Thomas A. Moreau, BSc, PhD, MCSE, MCDBA
SQL Server MVP
Columnist, SQL Server Professional
Toronto, ON Canada
www.pinnaclepublishing.com/sql
"Jonathan Lacefield" <Jonathan.lacefield@.solutionbuilders.com> wrote =in message news:002c01c376e5$98532500$a301280a@.phx.gbl...
I have been doing testing on tables sizes and I ran into a situation that I do not understand.
My default fill factor is set to 95%.
I used a SELECT INTO to copy a fact table for testing. The table was about 1.1 GB in size.
I then created a primary key /clustered index on an integer value on the new table. The table grew to about 1.9 GB in size.
I then truncated this table but left the index on it. I then ran an INSERT INTO statement to copy the origianl fact table.
The table was 1.1 GB in size and contained the clustered index.
Why would creating a clustered index increase a table's size when inserting into a table with an existing clustered index had no significant size difference? Doesn't the clustered index actually contain the data pages and therefore shouldn't affect the size of the table?
Thanks,
Jonathan Lacefield
MCDBA
--=_NextPart_000_0025_01C37769.7486AB40
Content-Type: text/html;
charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
&

Tibor, I don't believe that the space =is released after the rebuild. Let's say you had a single-file filegroups with =only one 100MB, non-indexed table in it. If you created a clustered =index on it, I'd expect the file to be about 220MB when completed. This =happens to me when I rebuild large tables. I see it in my file growth and the =free space available in the file.
-- Tom
----Thomas A. =Moreau, BSc, PhD, MCSE, MCDBASQL Server MVPColumnist, SQL Server ProfessionalToronto, ON Canadahttp://www.pinnaclepublishing.com/sql">www.pinnaclepublishing.com=/sql.
"Tibor Karaszi" wrote in message news:%23G$gqX4dDHA.=2804@.TK2MSFTNGP11.phx.gbl...
... but that should be released after =the rebuild is done. The question is, I guess, how Jonathan checked the space used =(file or table level)? If at table level, how was that done (sysindexes was =up-to-date or not)? Also, assuming that able level and correct info, what did DBCC =SHOWCONTIG say (avg page density)?
-- Tibor Karaszi, SQL Server MVPArchive at: http://groups.google.com/groups?oi=3Ddjq&as">http://groups.go=ogle.com/groups?oi=3Ddjq&as ugroup=3Dmicrosoft.public.sqlserver
"Tom Moreau" = wrote in message news:uw9AgZudDHA.3464=@.TK2MSFTNGP11.phx.gbl...
When you create or rebuild a =clustered index, SQL Server requires 1.2 X the size of the table in free space in order =to do the sort.
-- Tom

=---T=homas A. Moreau, BSc, PhD, MCSE, MCDBASQL Server MVPColumnist, SQL =Server ProfessionalToronto, ON Canadahttp://www.pinnaclepublishing.com/sql">www.pinnaclepublishing.com=/sql


"Jonathan Lacefield" wrote in message news:002c01c376e5$98=532500$a301280a@.phx.gbl...I have been doing testing on tables sizes and I ran into a situation =that I do not understand.My default fill factor is set to =95%.I used a SELECT INTO to copy a fact table for testing. The table =was about 1.1 GB in size.I then created a primary key /clustered index =on an integer value on the new table. The table grew to about =1.9 GB in size.I then truncated this table but left the index on =it. I then ran an INSERT INTO statement to copy the origianl fact table.The table was 1.1 GB in size and contained the clustered index.Why would creating a clustered index increase a =table's size when inserting into a table with an existing clustered =index had no significant size difference? Doesn't the clustered index =actually contain the data pages and therefore shouldn't affect the size of =the table?Thanks,Jonathan LacefieldMCDBA

--=_NextPart_000_0025_01C37769.7486AB40--|||This is a multi-part message in MIME format.
--=_NextPart_000_024D_01C3779C.3FF57400
Content-Type: text/plain;
charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable
Tom,
I was referring to the space *in* the database file (the "table size"). =Like a copy operation of a file. After you copied the file, the sectors =that the "old" file occupied are available for re-use. I agree that the =database file does not shrink in size after the create/rebuild.
-- Tibor Karaszi, SQL Server MVP
Archive at: http://groups.google.com/groups?oi=3Ddjq&as =ugroup=3Dmicrosoft.public.sqlserver
"Tom Moreau" <tom@.dont.spam.me.cips.ca> wrote in message =news:eiYE$r4dDHA.560@.tk2msftngp13.phx.gbl...
Tibor, I don't believe that the space is released after the rebuild. =Let's say you had a single-file filegroups with only one 100MB, =non-indexed table in it. If you created a clustered index on it, I'd =expect the file to be about 220MB when completed. This happens to me =when I rebuild large tables. I see it in my file growth and the free =space available in the file.
-- Tom
----
Thomas A. Moreau, BSc, PhD, MCSE, MCDBA
SQL Server MVP
Columnist, SQL Server Professional
Toronto, ON Canada
www.pinnaclepublishing.com/sql
.
"Tibor Karaszi" =<tibor.please_reply_to_public_forum.karaszi@.cornerstone.se> wrote in =message news:%23G$gqX4dDHA.2804@.TK2MSFTNGP11.phx.gbl...
... but that should be released after the rebuild is done. The =question is, I guess, how Jonathan checked the space used (file or table =level)? If at table level, how was that done (sysindexes was up-to-date =or not)? Also, assuming that able level and correct info, what did DBCC =SHOWCONTIG say (avg page density)?
-- Tibor Karaszi, SQL Server MVP
Archive at: http://groups.google.com/groups?oi=3Ddjq&as =ugroup=3Dmicrosoft.public.sqlserver
"Tom Moreau" <tom@.dont.spam.me.cips.ca> wrote in message =news:uw9AgZudDHA.3464@.TK2MSFTNGP11.phx.gbl...
When you create or rebuild a clustered index, SQL Server requires =1.2 X the size of the table in free space in order to do the sort.
-- Tom
---
Thomas A. Moreau, BSc, PhD, MCSE, MCDBA
SQL Server MVP
Columnist, SQL Server Professional
Toronto, ON Canada
www.pinnaclepublishing.com/sql
"Jonathan Lacefield" <Jonathan.lacefield@.solutionbuilders.com> wrote =in message news:002c01c376e5$98532500$a301280a@.phx.gbl...
I have been doing testing on tables sizes and I ran into a situation that I do not understand.
My default fill factor is set to 95%.
I used a SELECT INTO to copy a fact table for testing. The table was about 1.1 GB in size.
I then created a primary key /clustered index on an integer value on the new table. The table grew to about 1.9 GB in size.
I then truncated this table but left the index on it. I then ran an INSERT INTO statement to copy the origianl fact table.
The table was 1.1 GB in size and contained the clustered index.
Why would creating a clustered index increase a table's size when inserting into a table with an existing clustered index had no significant size difference? Doesn't the clustered index actually contain the data pages and therefore shouldn't affect the size of the table?
Thanks,
Jonathan Lacefield
MCDBA
--=_NextPart_000_024D_01C3779C.3FF57400
Content-Type: text/html;
charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
&

Tom,
I was referring to the space *in* the =database file (the "table size"). Like a copy operation of a file. After you copied =the file, the sectors that the "old" file occupied are available for re-use. I =agree that the database file does not shrink in size after the =create/rebuild.
-- Tibor Karaszi, SQL Server MVPArchive at: http://groups.google.com/groups?oi=3Ddjq&as">http://groups.go=ogle.com/groups?oi=3Ddjq&as ugroup=3Dmicrosoft.public.sqlserver
"Tom Moreau" = wrote in message news:eiYE$r4dDHA.560@.t=k2msftngp13.phx.gbl...
Tibor, I don't believe that the =space is released after the rebuild. Let's say you had a single-file =filegroups with only one 100MB, non-indexed table in it. If you created a =clustered index on it, I'd expect the file to be about 220MB when =completed. This happens to me when I rebuild large tables. I see it in my file =growth and the free space available in the file.
-- Tom

----Thomas A. =Moreau, BSc, PhD, MCSE, MCDBASQL Server MVPColumnist, SQL Server ProfessionalToronto, ON Canadahttp://www.pinnaclepublishing.com/sql">www.pinnaclepublishing.com=/sql.
"Tibor Karaszi" wrote in message news:%23G$gqX4dDHA.=2804@.TK2MSFTNGP11.phx.gbl...
... but that should be released after =the rebuild is done. The question is, I guess, how Jonathan checked the space used =(file or table level)? If at table level, how was that done (sysindexes was up-to-date or not)? Also, assuming that able level and correct info, =what did DBCC SHOWCONTIG say (avg page density)?
-- Tibor Karaszi, SQL Server MVPArchive at: http://groups.google.com/groups?oi=3Ddjq&as">http://groups.go=ogle.com/groups?oi=3Ddjq&as ugroup=3Dmicrosoft.public.sqlserver


"Tom Moreau" = wrote in message news:uw9AgZudDHA.3464=@.TK2MSFTNGP11.phx.gbl...
When you create or rebuild a =clustered index, SQL Server requires 1.2 X the size of the table in free space in =order to do the sort.
-- Tom

=---T=homas A. Moreau, BSc, PhD, MCSE, MCDBASQL Server MVPColumnist, SQL =Server ProfessionalToronto, ON Canadahttp://www.pinnaclepublishing.com/sql">www.pinnaclepublishing.com=/sql


"Jonathan Lacefield" wrote in message news:002c01c376e5$98=532500$a301280a@.phx.gbl...I have been doing testing on tables sizes and I ran into a =situation that I do not understand.My default fill factor is set to =95%.I used a SELECT INTO to copy a fact table for testing. The =table was about 1.1 GB in size.I then created a primary key /clustered =index on an integer value on the new table. The table grew =to about 1.9 GB in size.I then truncated this table but left the =index on it. I then ran an INSERT INTO statement to copy the =origianl fact table.The table was 1.1 GB in size and contained the =clustered index.Why would creating a clustered index increase a =table's size when inserting into a table with an existing clustered =index had no significant size difference? Doesn't the clustered =index actually contain the data pages and therefore shouldn't affect =the size of the table?Thanks,Jonathan LacefieldMCDBA

--=_NextPart_000_024D_01C3779C.3FF57400--|||This is a multi-part message in MIME format.
--=_NextPart_000_0023_01C37776.32723E60
Content-Type: text/plain;
charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable
OK, perhaps he should run DBCC UPDATEUSAGE (or sp_spaceused MyTable, =true) and see if that gives him the right numbers.
-- Tom
---
Thomas A. Moreau, BSc, PhD, MCSE, MCDBA
SQL Server MVP
Columnist, SQL Server Professional
Toronto, ON Canada
www.pinnaclepublishing.com/sql
"Tibor Karaszi" =<tibor.please_reply_to_public_forum.karaszi@.cornerstone.se> wrote in =message news:O2YRAu4dDHA.568@.TK2MSFTNGP11.phx.gbl...
Tom,
I was referring to the space *in* the database file (the "table size"). =Like a copy operation of a file. After you copied the file, the sectors =that the "old" file occupied are available for re-use. I agree that the =database file does not shrink in size after the create/rebuild.
-- Tibor Karaszi, SQL Server MVP
Archive at: http://groups.google.com/groups?oi=3Ddjq&as =ugroup=3Dmicrosoft.public.sqlserver
"Tom Moreau" <tom@.dont.spam.me.cips.ca> wrote in message =news:eiYE$r4dDHA.560@.tk2msftngp13.phx.gbl...
Tibor, I don't believe that the space is released after the rebuild. =Let's say you had a single-file filegroups with only one 100MB, =non-indexed table in it. If you created a clustered index on it, I'd =expect the file to be about 220MB when completed. This happens to me =when I rebuild large tables. I see it in my file growth and the free =space available in the file.
-- Tom
----
Thomas A. Moreau, BSc, PhD, MCSE, MCDBA
SQL Server MVP
Columnist, SQL Server Professional
Toronto, ON Canada
www.pinnaclepublishing.com/sql
.
"Tibor Karaszi" =<tibor.please_reply_to_public_forum.karaszi@.cornerstone.se> wrote in =message news:%23G$gqX4dDHA.2804@.TK2MSFTNGP11.phx.gbl...
... but that should be released after the rebuild is done. The =question is, I guess, how Jonathan checked the space used (file or table =level)? If at table level, how was that done (sysindexes was up-to-date =or not)? Also, assuming that able level and correct info, what did DBCC =SHOWCONTIG say (avg page density)?
-- Tibor Karaszi, SQL Server MVP
Archive at: http://groups.google.com/groups?oi=3Ddjq&as =ugroup=3Dmicrosoft.public.sqlserver
"Tom Moreau" <tom@.dont.spam.me.cips.ca> wrote in message =news:uw9AgZudDHA.3464@.TK2MSFTNGP11.phx.gbl...
When you create or rebuild a clustered index, SQL Server requires =1.2 X the size of the table in free space in order to do the sort.
-- Tom
---
Thomas A. Moreau, BSc, PhD, MCSE, MCDBA
SQL Server MVP
Columnist, SQL Server Professional
Toronto, ON Canada
www.pinnaclepublishing.com/sql
"Jonathan Lacefield" <Jonathan.lacefield@.solutionbuilders.com> wrote =in message news:002c01c376e5$98532500$a301280a@.phx.gbl...
I have been doing testing on tables sizes and I ran into a situation that I do not understand.
My default fill factor is set to 95%.
I used a SELECT INTO to copy a fact table for testing. The table was about 1.1 GB in size.
I then created a primary key /clustered index on an integer value on the new table. The table grew to about 1.9 GB in size.
I then truncated this table but left the index on it. I then ran an INSERT INTO statement to copy the origianl fact table.
The table was 1.1 GB in size and contained the clustered index.
Why would creating a clustered index increase a table's size when inserting into a table with an existing clustered index had no significant size difference? Doesn't the clustered index actually contain the data pages and therefore shouldn't affect the size of the table?
Thanks,
Jonathan Lacefield
MCDBA
--=_NextPart_000_0023_01C37776.32723E60
Content-Type: text/html;
charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
&

OK, perhaps he should run DBCC =UPDATEUSAGE (or sp_spaceused MyTable, true) and see if that gives him the right numbers.
-- Tom
---T=homas A. Moreau, BSc, PhD, MCSE, MCDBASQL Server MVPColumnist, SQL =Server ProfessionalToronto, ON Canadahttp://www.pinnaclepublishing.com/sql">www.pinnaclepublishing.com=/sql
"Tibor Karaszi" wrote in message news:O2YRAu4dDHA.568@.T=K2MSFTNGP11.phx.gbl...
Tom,
I was referring to the space *in* the =database file (the "table size"). Like a copy operation of a file. After you copied =the file, the sectors that the "old" file occupied are available for re-use. I =agree that the database file does not shrink in size after the =create/rebuild.
-- Tibor Karaszi, SQL Server MVPArchive at: http://groups.google.com/groups?oi=3Ddjq&as">http://groups.go=ogle.com/groups?oi=3Ddjq&as ugroup=3Dmicrosoft.public.sqlserver
"Tom Moreau" = wrote in message news:eiYE$r4dDHA.560@.t=k2msftngp13.phx.gbl...
Tibor, I don't believe that the =space is released after the rebuild. Let's say you had a single-file =filegroups with only one 100MB, non-indexed table in it. If you created a =clustered index on it, I'd expect the file to be about 220MB when =completed. This happens to me when I rebuild large tables. I see it in my file =growth and the free space available in the file.
-- Tom

----Thomas A. =Moreau, BSc, PhD, MCSE, MCDBASQL Server MVPColumnist, SQL Server ProfessionalToronto, ON Canadahttp://www.pinnaclepublishing.com/sql">www.pinnaclepublishing.com=/sql.
"Tibor Karaszi" wrote in message news:%23G$gqX4dDHA.=2804@.TK2MSFTNGP11.phx.gbl...
... but that should be released after =the rebuild is done. The question is, I guess, how Jonathan checked the space used =(file or table level)? If at table level, how was that done (sysindexes was up-to-date or not)? Also, assuming that able level and correct info, =what did DBCC SHOWCONTIG say (avg page density)?
-- Tibor Karaszi, SQL Server MVPArchive at: http://groups.google.com/groups?oi=3Ddjq&as">http://groups.go=ogle.com/groups?oi=3Ddjq&as ugroup=3Dmicrosoft.public.sqlserver


"Tom Moreau" = wrote in message news:uw9AgZudDHA.3464=@.TK2MSFTNGP11.phx.gbl...
When you create or rebuild a =clustered index, SQL Server requires 1.2 X the size of the table in free space in =order to do the sort.
-- Tom

=---T=homas A. Moreau, BSc, PhD, MCSE, MCDBASQL Server MVPColumnist, SQL =Server ProfessionalToronto, ON Canadahttp://www.pinnaclepublishing.com/sql">www.pinnaclepublishing.com=/sql


"Jonathan Lacefield" wrote in message news:002c01c376e5$98=532500$a301280a@.phx.gbl...I have been doing testing on tables sizes and I ran into a =situation that I do not understand.My default fill factor is set to =95%.I used a SELECT INTO to copy a fact table for testing. The =table was about 1.1 GB in size.I then created a primary key /clustered =index on an integer value on the new table. The table grew =to about 1.9 GB in size.I then truncated this table but left the =index on it. I then ran an INSERT INTO statement to copy the =origianl fact table.The table was 1.1 GB in size and contained the =clustered index.Why would creating a clustered index increase a =table's size when inserting into a table with an existing clustered =index had no significant size difference? Doesn't the clustered =index actually contain the data pages and therefore shouldn't affect =the size of the table?Thanks,Jonathan LacefieldMCDBA

--=_NextPart_000_0023_01C37776.32723E60--|||This is a multi-part message in MIME format.
--=_NextPart_000_0009_01C377AA.4FD990F0
Content-Type: text/plain;
charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable
Yep!
-- Tibor Karaszi, SQL Server MVP
Archive at: http://groups.google.com/groups?oi=3Ddjq&as =ugroup=3Dmicrosoft.public.sqlserver
"Tom Moreau" <tom@.dont.spam.me.cips.ca> wrote in message =news:OWw3te5dDHA.3680@.TK2MSFTNGP11.phx.gbl...
OK, perhaps he should run DBCC UPDATEUSAGE (or sp_spaceused MyTable, =true) and see if that gives him the right numbers.
-- Tom
---
Thomas A. Moreau, BSc, PhD, MCSE, MCDBA
SQL Server MVP
Columnist, SQL Server Professional
Toronto, ON Canada
www.pinnaclepublishing.com/sql
"Tibor Karaszi" =<tibor.please_reply_to_public_forum.karaszi@.cornerstone.se> wrote in =message news:O2YRAu4dDHA.568@.TK2MSFTNGP11.phx.gbl...
Tom,
I was referring to the space *in* the database file (the "table =size"). Like a copy operation of a file. After you copied the file, the =sectors that the "old" file occupied are available for re-use. I agree =that the database file does not shrink in size after the create/rebuild.
-- Tibor Karaszi, SQL Server MVP
Archive at: http://groups.google.com/groups?oi=3Ddjq&as =ugroup=3Dmicrosoft.public.sqlserver
"Tom Moreau" <tom@.dont.spam.me.cips.ca> wrote in message =news:eiYE$r4dDHA.560@.tk2msftngp13.phx.gbl...
Tibor, I don't believe that the space is released after the rebuild. = Let's say you had a single-file filegroups with only one 100MB, =non-indexed table in it. If you created a clustered index on it, I'd =expect the file to be about 220MB when completed. This happens to me =when I rebuild large tables. I see it in my file growth and the free =space available in the file.
-- Tom
----
Thomas A. Moreau, BSc, PhD, MCSE, MCDBA
SQL Server MVP
Columnist, SQL Server Professional
Toronto, ON Canada
www.pinnaclepublishing.com/sql
.
"Tibor Karaszi" =<tibor.please_reply_to_public_forum.karaszi@.cornerstone.se> wrote in =message news:%23G$gqX4dDHA.2804@.TK2MSFTNGP11.phx.gbl...
... but that should be released after the rebuild is done. The =question is, I guess, how Jonathan checked the space used (file or table =level)? If at table level, how was that done (sysindexes was up-to-date =or not)? Also, assuming that able level and correct info, what did DBCC =SHOWCONTIG say (avg page density)?
-- Tibor Karaszi, SQL Server MVP
Archive at: http://groups.google.com/groups?oi=3Ddjq&as =ugroup=3Dmicrosoft.public.sqlserver
"Tom Moreau" <tom@.dont.spam.me.cips.ca> wrote in message =news:uw9AgZudDHA.3464@.TK2MSFTNGP11.phx.gbl...
When you create or rebuild a clustered index, SQL Server requires =1.2 X the size of the table in free space in order to do the sort.
-- Tom
---
Thomas A. Moreau, BSc, PhD, MCSE, MCDBA
SQL Server MVP
Columnist, SQL Server Professional
Toronto, ON Canada
www.pinnaclepublishing.com/sql
"Jonathan Lacefield" <Jonathan.lacefield@.solutionbuilders.com> =wrote in message news:002c01c376e5$98532500$a301280a@.phx.gbl...
I have been doing testing on tables sizes and I ran into a situation that I do not understand.
My default fill factor is set to 95%.
I used a SELECT INTO to copy a fact table for testing. The table was about 1.1 GB in size.
I then created a primary key /clustered index on an integer value on the new table. The table grew to about 1.9 GB in size.
I then truncated this table but left the index on it. I then ran an INSERT INTO statement to copy the origianl fact table.
The table was 1.1 GB in size and contained the clustered index.
Why would creating a clustered index increase a table's size when inserting into a table with an existing clustered index had no significant size difference? Doesn't the clustered index actually contain the data pages and therefore shouldn't affect the size of the table?
Thanks,
Jonathan Lacefield
MCDBA
--=_NextPart_000_0009_01C377AA.4FD990F0
Content-Type: text/html;
charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
&

Yep!
-- Tibor Karaszi, SQL Server MVPArchive at: http://groups.google.com/groups?oi=3Ddjq&as">http://groups.go=ogle.com/groups?oi=3Ddjq&as ugroup=3Dmicrosoft.public.sqlserver
"Tom Moreau" = wrote in message news:OWw3te5dDHA.3680=@.TK2MSFTNGP11.phx.gbl...
OK, perhaps he should run DBCC =UPDATEUSAGE (or sp_spaceused MyTable, true) and see if that gives him the right numbers.
-- Tom

=---T=homas A. Moreau, BSc, PhD, MCSE, MCDBASQL Server MVPColumnist, SQL =Server ProfessionalToronto, ON Canadahttp://www.pinnaclepublishing.com/sql">www.pinnaclepublishing.com=/sql


"Tibor Karaszi" wrote in message news:O2YRAu4dDHA.568@.T=K2MSFTNGP11.phx.gbl...
Tom,

I was referring to the space *in* the =database file (the "table size"). Like a copy operation of a file. After you =copied the file, the sectors that the "old" file occupied are available for =re-use. I agree that the database file does not shrink in size after the create/rebuild.
-- Tibor Karaszi, SQL Server MVPArchive at: http://groups.google.com/groups?oi=3Ddjq&as">http://groups.go=ogle.com/groups?oi=3Ddjq&as ugroup=3Dmicrosoft.public.sqlserver


"Tom Moreau" = wrote in message news:eiYE$r4dDHA.560@.t=k2msftngp13.phx.gbl...
Tibor, I don't believe that the =space is released after the rebuild. Let's say you had a single-file =filegroups with only one 100MB, non-indexed table in it. If you created a = clustered index on it, I'd expect the file to be about 220MB when completed. This happens to me when I rebuild large =tables. I see it in my file growth and the free space available in the =file.
-- Tom

----Thomas =A. Moreau, BSc, PhD, MCSE, MCDBASQL Server MVPColumnist, SQL =Server ProfessionalToronto, ON Canadahttp://www.pinnaclepublishing.com/sql">www.pinnaclepublishing.com=/sql.
"Tibor Karaszi" wrote in message news:%23G$gqX4dDHA.=2804@.TK2MSFTNGP11.phx.gbl...
... but that should be released =after the rebuild is done. The question is, I guess, how Jonathan checked the =space used (file or table level)? If at table level, how was that done =(sysindexes was up-to-date or not)? Also, assuming that able level and correct =info, what did DBCC SHOWCONTIG say (avg page density)?
-- Tibor Karaszi, SQL Server MVPArchive at: http://groups.google.com/groups?oi=3Ddjq&as">http://groups.go=ogle.com/groups?oi=3Ddjq&as ugroup=3Dmicrosoft.public.sqlserver


"Tom Moreau" = wrote in message news:uw9AgZudDHA.3464=@.TK2MSFTNGP11.phx.gbl...
When you create or rebuild a =clustered index, SQL Server requires 1.2 X the size of the table in free =space in order to do the sort.
-- Tom

=---T=homas A. Moreau, BSc, PhD, MCSE, MCDBASQL Server MVPColumnist, =SQL Server ProfessionalToronto, ON Canadahttp://www.pinnaclepublishing.com/sql">www.pinnaclepublishing.com=/sql


"Jonathan Lacefield" wrote in message news:002c01c376e5$98=532500$a301280a@.phx.gbl...I have been doing testing on tables sizes and I ran into a =situation that I do not understand.My default fill factor is set to 95%.I used a SELECT INTO to copy a fact table for =testing. The table was about 1.1 GB in size.I then created a =primary key /clustered index on an integer value on the new =table. The table grew to about 1.9 GB in size.I then =truncated this table but left the index on it. I then ran an INSERT =INTO statement to copy the origianl fact table.The table was =1.1 GB in size and contained the clustered index.Why would =creating a clustered index increase a table's size when inserting into a =table with an existing clustered index had no significant size difference? Doesn't the clustered index actually contain =the data pages and therefore shouldn't affect the size of the table?Thanks,Jonathan LacefieldMCDBA

--=_NextPart_000_0009_01C377AA.4FD990F0--|||It will take me a day or two to get the Stats on the
table. I used this table for testing and then dropped it
when I had completed the testing. I appreciate tour help
and info.
THanks
>--Original Message--
>Yep!
>--
>Tibor Karaszi, SQL Server MVP
>Archive at: http://groups.google.com/groups?oi=djq&as
ugroup=microsoft.public.sqlserver
>
> "Tom Moreau" <tom@.dont.spam.me.cips.ca> wrote in
message news:OWw3te5dDHA.3680@.TK2MSFTNGP11.phx.gbl...
> OK, perhaps he should run DBCC UPDATEUSAGE (or
sp_spaceused MyTable, true) and see if that gives him the
right numbers.
> --
> Tom
> ---
--
> Thomas A. Moreau, BSc, PhD, MCSE, MCDBA
> SQL Server MVP
> Columnist, SQL Server Professional
> Toronto, ON Canada
> www.pinnaclepublishing.com/sql
>
> "Tibor Karaszi"
<tibor.please_reply_to_public_forum.karaszi@.cornerstone.se>
wrote in message
news:O2YRAu4dDHA.568@.TK2MSFTNGP11.phx.gbl...
> Tom,
> I was referring to the space *in* the database file
(the "table size"). Like a copy operation of a file. After
you copied the file, the sectors that the "old" file
occupied are available for re-use. I agree that the
database file does not shrink in size after the
create/rebuild.
> --
> Tibor Karaszi, SQL Server MVP
> Archive at: http://groups.google.com/groups?oi=djq&as
ugroup=microsoft.public.sqlserver
>
> "Tom Moreau" <tom@.dont.spam.me.cips.ca> wrote in
message news:eiYE$r4dDHA.560@.tk2msftngp13.phx.gbl...
> Tibor, I don't believe that the space is released
after the rebuild. Let's say you had a single-file
filegroups with only one 100MB, non-indexed table in it.
If you created a clustered index on it, I'd expect the
file to be about 220MB when completed. This happens to me
when I rebuild large tables. I see it in my file growth
and the free space available in the file.
> --
> Tom
> ----
> Thomas A. Moreau, BSc, PhD, MCSE, MCDBA
> SQL Server MVP
> Columnist, SQL Server Professional
> Toronto, ON Canada
> www.pinnaclepublishing.com/sql
> .
> "Tibor Karaszi"
<tibor.please_reply_to_public_forum.karaszi@.cornerstone.se>
wrote in message news:%
23G$gqX4dDHA.2804@.TK2MSFTNGP11.phx.gbl...
> ... but that should be released after the rebuild is
done. The question is, I guess, how Jonathan checked the
space used (file or table level)? If at table level, how
was that done (sysindexes was up-to-date or not)? Also,
assuming that able level and correct info, what did DBCC
SHOWCONTIG say (avg page density)?
> --
> Tibor Karaszi, SQL Server MVP
> Archive at: http://groups.google.com/groups?oi=djq&as
ugroup=microsoft.public.sqlserver
>
> "Tom Moreau" <tom@.dont.spam.me.cips.ca> wrote in
message news:uw9AgZudDHA.3464@.TK2MSFTNGP11.phx.gbl...
> When you create or rebuild a clustered index, SQL
Server requires 1.2 X the size of the table in free space
in order to do the sort.
> --
> Tom
> ----
--
> Thomas A. Moreau, BSc, PhD, MCSE, MCDBA
> SQL Server MVP
> Columnist, SQL Server Professional
> Toronto, ON Canada
> www.pinnaclepublishing.com/sql
>
> "Jonathan Lacefield"
<Jonathan.lacefield@.solutionbuilders.com> wrote in message
news:002c01c376e5$98532500$a301280a@.phx.gbl...
> I have been doing testing on tables sizes and I ran
into a
> situation that I do not understand.
> My default fill factor is set to 95%.
> I used a SELECT INTO to copy a fact table for
testing.
> The table was about 1.1 GB in size.
> I then created a primary key /clustered index on an
> integer value on the new table.
> The table grew to about 1.9 GB in size.
> I then truncated this table but left the index on
it.
> I then ran an INSERT INTO statement to copy the
origianl
> fact table.
> The table was 1.1 GB in size and contained the
clustered
> index.
> Why would creating a clustered index increase a
table's
> size when inserting into a table with an existing
> clustered index had no significant size
difference?
> Doesn't the clustered index actually contain the
data
> pages and therefore shouldn't affect the size of
the table?
> Thanks,
> Jonathan Lacefield
> MCDBA