Showing posts with label statement. Show all posts
Showing posts with label statement. Show all posts

Thursday, March 29, 2012

Create Table within an IF statement causes error

This doesn't make any sense to me. I am trying to create a stored procedure that creates a temp table using T-SQL. The table will be created differently depending on the arguments passed. Here is an example of what I am trying to do:

DECLARE @.Switch bit

SET @.Switch = 0

IF @.Switch = 0

BEGIN

PRINT @.Switch

CREATE TABLE #DontWork (Zero int)

END

ELSE

BEGIN

PRINT @.Switch

CREATE TABLE #DontWork (One int)

END

SELECT * FROM #DontWork

If you run this as is, it fails stating that "There is already an object named '#DontWork' in the database." However if you comment out one of the CREATE TABLE statements (either one of them), it works fine. The PRINT @.Switch line will prove that the IF ELSE statement is evaluating properly if you change the value of @.Switch. My guess is that the parsing engine is throwing the error before it even tries to run the code. Is there any way to make this work the way it should? Or do I have to resort to creating 2 different tables and modifying the rest of my code to compensate for the change?

This is usually caused because you have ran a CREATE TABLE statement in a previous development iteration. Try appending this to the end of your code:

Code Snippet

go

drop table #DontWork

The temp table stays in scope after you run through one time so the next time through you get the error. Try hiliting the code I've given you and execute just the DROP TABLE. Then un-hilite the code and rerun query. It should run correctly once you have dropped the table.

OK, I'm all wet... Hang on.

You can alter it:

Code Snippet

create table #what (one int)

alter table #what
add two int

alter table #what
drop column one

select * from #what

go

drop table #what

/*
two
--
*/

|||

The code doesn't execute.

The parsing engine is attempting to resolve the objects, and (incorrectly, in my opinion) assumes that the second instance of the create table is attempting to make a second object with the same name. The parsing engine is resolving objects, not checking logic and code flow.

To test, comment out EITHER CREATE statement and the code executes.

Your options include creating the #Temp table before the IF statement, or using a different #Table name in the second instance.

Or you could have both switched locations call out to another procedure that creates the #Temp table.

|||My code already involves altering the table. I was just trying to use an IF statement because one scenario creates a predictable table structure, and the other side requires that the field names be calculated at run time. I was trying to save myself some effort by simply having that CREATE TABLE command in there twice, but it seems that because of what Arnie said about the parsing engine resolving objects, not checking logic and code flow, I'm going to have to do things the complicated way. I wish there was a way to communicate things like this to the powers that be at Microsoft. Any idea how to do that, if at all possible?|||

They do pay attention to the suggestions.

Suggestions for SQL Server

http://connect.microsoft.com/sqlserver

|||MS SQL has always had a problem with this construct. The solution, as mentioned, is to create the table once, and then use alter table to change the table to what you want. Or just create 2 tables of different names.

|||

SQL Server compiles the entire batch (SP, trigger, function or ad-hoc) and compilation doesn't take into account run-time information (variable values, control of flow etc). This gets tricky for temporary tables because of the way they are scoped. For best performance and manageability, you should put the creation logic for the different conditions in their own SPs and the execution logic too. This provides better reusability. You could use the ALTER TABLE approach but that will give bad performance in SQL Server 2005 since it negates the caching that we do automatically on temporary tables (metadata & 1 page of allocation which can get reused). Of course, if you can remove the temporary tables altogether.

Btw, your code will work if you were creating a permanent table conditionally.

create table statement

I need to create duplicates of certain tables.
It woud be great if i can find the 'create table statement', in any of
the system tables which the Create Table of the Object Browser in
Query Analyzer users, so that i can just change the name and create a
new table thus.
Please help me find the Create Table statement available in the system
tables
thank you
Right click on the table in SSMS object browser, select Script Table As ->
CREATE to -> New Query Window
Anith
|||Unfortunately, the ddl is not stored in the system tables. You can script
the tables from EM or SSMS though.
Jason Massie
Web: http://statisticsio.com
RSS: http://feeds.feedburner.com/statisticsio
<thetaamommy@.gmail.com> wrote in message
news:1c72f9e7-1052-40c3-8a2d-0f72a4e4c5bf@.c33g2000hsd.googlegroups.com...
>I need to create duplicates of certain tables.
> It woud be great if i can find the 'create table statement', in any of
> the system tables which the Create Table of the Object Browser in
> Query Analyzer users, so that i can just change the name and create a
> new table thus.
> Please help me find the Create Table statement available in the system
> tables
> thank you
sql

create table statement

I need to create duplicates of certain tables.
It woud be great if i can find the 'create table statement', in any of
the system tables which the Create Table of the Object Browser in
Query Analyzer users, so that i can just change the name and create a
new table thus.
Please help me find the Create Table statement available in the system
tables
thank youRight click on the table in SSMS object browser, select Script Table As ->
CREATE to -> New Query Window
--
Anith|||Unfortunately, the ddl is not stored in the system tables. You can script
the tables from EM or SSMS though.
--
Jason Massie
Web: http://statisticsio.com
RSS: http://feeds.feedburner.com/statisticsio
<thetaamommy@.gmail.com> wrote in message
news:1c72f9e7-1052-40c3-8a2d-0f72a4e4c5bf@.c33g2000hsd.googlegroups.com...
>I need to create duplicates of certain tables.
> It woud be great if i can find the 'create table statement', in any of
> the system tables which the Create Table of the Object Browser in
> Query Analyzer users, so that i can just change the name and create a
> new table thus.
> Please help me find the Create Table statement available in the system
> tables
> thank you|||Yes it's like he says
And you can do this also in your Query Analyaer (Right Click on your table I
mean) ;)
Arjen
"Anith Sen" <anith@.bizdatasolutions.com> schreef in bericht
news:u9MPgoUfIHA.4712@.TK2MSFTNGP04.phx.gbl...
> Right click on the table in SSMS object browser, select Script Table As ->
> CREATE to -> New Query Window
> --
> Anith
>

Tuesday, March 27, 2012

create table from select result

Hi,
I need to create a table which has the columns from the select statement result.
I tried in this way
drop table j9a
SELECT er.* into j9a
FROM caCase c
LEFT OUTER JOIN paPatient pp ON c.caCaseID=pp.caCaseID
Left Outer JOIN paManagementSite pm ON pp.paManagementSiteID=pm.paManagementSiteID
Left Join exexposure ee ON ee.cacaseID=c.caCaseID
LEFT OUTER JOIN exExposureRoute eer ON eer.caCaseID=c.caCaseID
LEFT OUTER JOIN exRoute er ON er.exRouteID=eer.exRouteID
WHERE c.caCallTypeID =0
AND c.Startdate between '1/1/2006' and '12/1/2006'
AND (ee.exMedicalOutcomeID=4 OR ee.exMedicalOutcomeID=10)
AND pp.paSpeciesID=1
AND c.PublicID_adOrganization_secondary is null
declare @.1 int,@.2 int,@.3 int,@.4 int,@.5 int,@.6 int,@.7 int,@.8 int,
@.9 int,@.10 int,@.11 int,@.12 int,@.21 int,@.22 int,@.23 int,@.24 int,@.25 int,
@.26 int,@.27 int,@.28 int,@.29 int,@.30 int,@.31 int,@.32 int
set @.21=(select count(*) from j9a where Ingestion=1)
set @.22=(select count(*) from j9a where Inhalation=1)
set @.23=(select count(*) from j9a where Aspiration=1)
set @.24=(select count(*) from j9a where Ocular=1)
set @.25=(select count(*) from j9a where Dermal=1)
set @.26=(select count(*) from j9a where Bite=1)
set @.27=(select count(*) from j9a where Parenteral=1)
set @.28=(select count(*) from j9a where Otic=1)
set @.29=(select count(*) from j9a where Rectal=1)
set @.30=(select count(*) from j9a where Vaginal=1)
set @.31=(select count(*) from j9a where Other=1)
set @.32=(select count(*) from j9a where Unknown=1)
The exRoute result is like this
70 Ingestion
71 Inhalation/nasal
72 Aspiration (with ingestion)
73 Ocular
74 Dermal
75 Bite/sting
76 Parenteral
77 Other
78 Unknown
524 Otic
525 Rectal
526 Vaginal
The above giving the errors Msg 207, Level 16, State 1, Line 19
Invalid column name 'Route_Ingestion'.
Msg 207, Level 16, State 1, Line 20
Invalid column name 'Route_Inhalation'
How to create table j9a.j9a has the columns from select
Thanks in advance
Are the columns [Route_Ingestion] and [Route_Inhalation] in the table exRoute?
|||

Hi,

I modified the post,can you please look at that

|||

With your lastest modification, do you still get the same error?

It would be helpful if you were to post the entire set of code. Your error message indicates that somewhere in the code you are requesting something to do with columns named [Route_Ingestion] and [Route_Inhalation]. Perhaps there is an error with the column names somewhere, but without being able to see the entire bit of code, it is impossible to help you.

Msg 207, Level 16, State 1, Line 19
Invalid column name 'Route_Ingestion'.
Msg 207, Level 16, State 1, Line 20
Invalid column name 'Route_Inhalation'

|||

Hi,

My complete code is

drop table j9a

SELECT er.* into j9a

FROM caCase c

LEFT OUTER JOIN paPatient pp ON c.caCaseID=pp.caCaseID

Left Outer JOIN paManagementSite pm ON pp.paManagementSiteID=pm.paManagementSiteID

Left Join exexposure ee ON ee.cacaseID=c.caCaseID

LEFT OUTER JOIN exExposureRoute eer ON eer.caCaseID=c.caCaseID

LEFT OUTER JOIN exRoute er ON er.exRouteID=eer.exRouteID

WHERE c.caCallTypeID =0

AND c.Startdate between '1/1/2006' and '12/1/2006'

AND (ee.exMedicalOutcomeID=4 OR ee.exMedicalOutcomeID=10)

AND pp.paSpeciesID=1

AND c.PublicID_adOrganization_secondary is null

declare @.1 int,@.2 int,@.3 int,@.4 int,@.5 int,@.6 int,@.7 int,@.8 int,

@.9 int,@.10 int,@.11 int,@.12 int,@.21 int,@.22 int,@.23 int,@.24 int,@.25 int,

@.26 int,@.27 int,@.28 int,@.29 int,@.30 int,@.31 int,@.32 int

set @.21=(select count(*) from j9a where Ingestion=1)

set @.22=(select count(*) from j9a where Inhalation=1)

set @.23=(select count(*) from j9a where Aspiration=1)

set @.24=(select count(*) from j9a where Ocular=1)

set @.25=(select count(*) from j9a where Dermal=1)

set @.26=(select count(*) from j9a where Bite=1)

set @.27=(select count(*) from j9a where Parenteral=1)

set @.28=(select count(*) from j9a where Otic=1)

set @.29=(select count(*) from j9a where Rectal=1)

set @.30=(select count(*) from j9a where Vaginal=1)

set @.31=(select count(*) from j9a where Other=1)

set @.32=(select count(*) from j9a where Unknown=1)

Create table table9(Route varchar(30),Fatal int)

insert into table9 values ('Ingestion',@.1,@.21)

insert into table9 values ('Inhalation',@.2,@.22)

insert into table9 values ('Aspiration',@.3,@.23)

insert into table9 values ('Ocular',@.4,@.24)

insert into table9 values ('Dermal',@.5,@.25)

insert into table9 values ('Bite',@.6,@.26)

insert into table9 values ('Parenteral',@.7,@.27)

insert into table9 values ('Otic',@.8,@.28)

insert into table9 values ('Rectal',@.9,@.29)

insert into table9 values ('Vaginal',@.10,@.30)

insert into table9 values ('Other',@.11,@.31)

insert into table9 values ('Unknown',@.12,@.32)

select * from table9

and Select exrouteid,name from exRoute;

Will give results like this

70 Ingestion
71 Inhalation
72 Aspiration 73 Ocular
74 Dermal
75 Bite/sting
76 Parenteral
77 Other
78 Unknown
524 Otic
525 Rectal
526 Vaginal

But still iam getting errors Like

Invalid column name 'Ingestion'.

For all columns this error is coming

Thanks in advance

|||

There is a whole 'mess' of problems here.

First, Table j9a (which comes from exRount) contains does not appear to contain columns named 'Ingestion', 'Inhalation', etc. ( Select exrouteid,name from exRoute ) Those are values stored in the column named 'Name'. Therefore all of the variable assignments using SELECT will fail since they are requesting data from a column named 'Ingestion', etc. ( set @.21=(select count(*) from j9a where Ingestion=1) )

Then you create a table [Table9], which has two (2) columns, (Create table table9(Route varchar(30),Fatal int)) and attempt to INSERT three values into that table. ( insert into table9 values ('Ingestion',@.1,@.21))

There may be additional problems, but I stopped lookiing at this point. Apparantly, you are attempting to so something a bit more complex that your current skills. (Nothing wrong with that, we all have to learn and progress.) But this code cannot work, and is most likely NOT the best way to create a solution.

I suggest that you post the TABLE DDL, some sample data in the form of INSERT Statements, and a description of what you are attempting to accomplish and perhaps we can help you. See this link for help in preparing the information we need in order to help you. http://www.aspfaq.com/5006

|||

Hi,

I found where the problem is.

I modified the stored procedure entirely.

Now iam getting the result

Thanks

create table from output of select sql

I want to create a table with the output of select statement. i.e. create
table tmpk as select *...
this gives an error
Incorrect syntax near the keyword 'as'.
when i am running query alone this gives the result fine.try
SELECT
field1, field 2 etc...
INTO tmpk
FROM
wherever
"Karn Tanwar" <karntanwer@.hotmail.com> wrote in message
news:OtJceVhVFHA.544@.TK2MSFTNGP15.phx.gbl...
> I want to create a table with the output of select statement. i.e. create
> table tmpk as select *...
> this gives an error
> Incorrect syntax near the keyword 'as'.
> when i am running query alone this gives the result fine.
>|||On Wed, 11 May 2005 16:21:36 +0530, Karn Tanwar wrote:

> I want to create a table with the output of select statement. i.e. create
> table tmpk as select *...
You have to use EXEC, like this:
DECLARE @.var VARCHAR(8000)
SELECT @.var = 'CREATE TABLE ' + something
FROM somewhere
WHERE somecol = @.somevar
EXEC (@.var)
This is a crude example, but you get the point.
/Andrs Taylor|||Hi Karan
Try this way
SELECT * INTO tmpk FROM ...
best Regards,
Chandra
http://chanduas.blogspot.com/
---
"Karn Tanwar" wrote:

> I want to create a table with the output of select statement. i.e. create
> table tmpk as select *...
> this gives an error
> Incorrect syntax near the keyword 'as'.
> when i am running query alone this gives the result fine.
>
>|||Unfortunately in the SQL Server enviornment you cannot select into a table
like you can in other legacy enviornments like Foxpro but you can declare a
local temp table with the same field makeup as the select statement outputs
and then use and insert to get the data into a table. You might have to mes
s
with it for a little while before you get it right, but it is possible to ge
t
somewhat the same results.
Declare @.v_sql NVARCHAR(4000)
SELECT @.v_sql =
INSERT #test
select hard_id,
Type_id,
description,
speed,
amount,
cache,
brand
from TU_Hardware
EXEC sp_executesql @.v_sql
"Karn Tanwar" wrote:

> I want to create a table with the output of select statement. i.e. create
> table tmpk as select *...
> this gives an error
> Incorrect syntax near the keyword 'as'.
> when i am running query alone this gives the result fine.
>
>|||Correction.. you can do a select into statement but you cant do it the way
you were trying it.
If you go to masters table on any db and type the following:
select * from abc
It will give you an error because no table exist then type
select top 10 *
into abc
from sysobjects
You will have a new table in master db. You can do this with any table in
the from part of the statement.
Hope this helps..
"Karn Tanwar" wrote:

> I want to create a table with the output of select statement. i.e. create
> table tmpk as select *...
> this gives an error
> Incorrect syntax near the keyword 'as'.
> when i am running query alone this gives the result fine.
>
>

Thursday, March 22, 2012

CREATE SUBCUBE Syntax and Example

Can anyone provide an example of the right syntax for the CREATE SUBCUBE statement? And possibly discuss its use a bit? For example, from a client tool (like Excel), would there be any way to execute a CREATE SUBCUBE statement such that all browsing done within Excel was bound by the scope of the subcube? While perspectives provide a great server-based mechanism for creating scoped sections of a cube, I need a way to do this on the fly, from a client tool like Excel.

Thanks,
Dave Fackler
Just to follow-up on this for everyone else, I determined what syntax to use for the CREATE SUBCUBE statement. If you use the Browse window in BI Dev Studio or SS Management Studio, you can now define filters that the OWC control then respects as you drag and drop dimensions onto the rows and columns of the pivot table.

So, if you fire up Profiler and start a trace on Analysis Services, then use the Browse window to create a query with filters applied, you'll see the CREATE SUBCUBE statement come across. Very informative as you'll also see a host of other commands being executed by the Browse window!

At any rate, the CREATE SUBCUBE statement simply needs to contain a list of the filters you want in place defined on the columns axis of a standard select statement. Thus, the following would create a subcube on the Adventure Works database for just 2003 and 2004 in the US and UK:

CREATE SUBCUBE [Adventure Works] AS

SELECT ({[Customer].[Country].[United States], [Customer].[Country].[United Kingdom]}, {[Date].[Calendar Year].[CY 2003], [Date].[Calendar Year].[CY 2004]}) ON COLUMNS FROM [Adventure Works]

Notice that the subcube has the same name as the original cube in this example. It doesn't have to, but it can. Any subsequent queries to [Adventure Works] in the current session would then use the subcube and be limited to its scope.

Once the need for the subcube is gone, you can manually drop it as follows:

DROP SUBCUBE [Adventure Works]

This is exactly what the Browse windows in BI Dev Studio and SS Management Studio do (along with some other interesting statements).

Kudos to Profiler for helping me discover this on my own!!

Dave Fackler
|||

Hi Dave,

Some times it possible to have same result in MDX either by using CREATE SUBCUBE or by using FILETR function. Which method is better?

Regadrs,
Rakesh

CREATE SUBCUBE Syntax and Example

Can anyone provide an example of the right syntax for the CREATE SUBCUBE statement? And possibly discuss its use a bit? For example, from a client tool (like Excel), would there be any way to execute a CREATE SUBCUBE statement such that all browsing done within Excel was bound by the scope of the subcube? While perspectives provide a great server-based mechanism for creating scoped sections of a cube, I need a way to do this on the fly, from a client tool like Excel.

Thanks,
Dave Fackler
Just to follow-up on this for everyone else, I determined what syntax to use for the CREATE SUBCUBE statement. If you use the Browse window in BI Dev Studio or SS Management Studio, you can now define filters that the OWC control then respects as you drag and drop dimensions onto the rows and columns of the pivot table.

So, if you fire up Profiler and start a trace on Analysis Services, then use the Browse window to create a query with filters applied, you'll see the CREATE SUBCUBE statement come across. Very informative as you'll also see a host of other commands being executed by the Browse window!

At any rate, the CREATE SUBCUBE statement simply needs to contain a list of the filters you want in place defined on the columns axis of a standard select statement. Thus, the following would create a subcube on the Adventure Works database for just 2003 and 2004 in the US and UK:

CREATE SUBCUBE [Adventure Works] AS

SELECT ({[Customer].[Country].[United States], [Customer].[Country].[United Kingdom]}, {[Date].[Calendar Year].[CY 2003], [Date].[Calendar Year].[CY 2004]}) ON COLUMNS FROM [Adventure Works]

Notice that the subcube has the same name as the original cube in this example. It doesn't have to, but it can. Any subsequent queries to [Adventure Works] in the current session would then use the subcube and be limited to its scope.

Once the need for the subcube is gone, you can manually drop it as follows:

DROP SUBCUBE [Adventure Works]

This is exactly what the Browse windows in BI Dev Studio and SS Management Studio do (along with some other interesting statements).

Kudos to Profiler for helping me discover this on my own!!

Dave Fackler
|||

Hi Dave,

Some times it possible to have same result in MDX either by using CREATE SUBCUBE or by using FILETR function. Which method is better?

Regadrs,
Rakesh

sql

Wednesday, March 21, 2012

Create SQL INSERT STATEMENT WITHOUT KNOWING THE TABLE NAME... in a tirgger

I have a process I have inherited that requires me to create an insert statement, but the kicker is that I will not know the temp table's name ahead of time until it has been created. Now my code works as is, but it complains about the syntax and I was hoping there might be a better way of doing this. The code I would like to change is in orange.

Anyway, any advice would be greatly appreciated...

Here is the basic trigger:

Code Snippet

ALTER TRIGGER [dbo].[trg_DownloadDataTypes_ins] ON [dbo].[DownloadDataTypes]

INSTEAD OF INSERT

AS

SET NOCOUNT OFF

DECLARE @.TableName varchar(100),

@.FileType varchar(100),

@.FileName varchar(100),

@.CampusID varchar(15),

@.DateCreated DateTime,

@.ParentID int

IF (SELECT COUNT(FileName) FROM INSERTED) = 1

BEGIN

SELECT @.TableName = (SELECT [FileName] FROM INSERTED)

SELECT @.FileName = (SELECT [FileName] FROM INSERTED)

SELECT @.FileType = (SELECT FileType FROM INSERTED)

SELECT @.CampusID = (SELECT CampusID FROM INSERTED)

SELECT @.DateCreated = (SELECT DateDownLoaded FROM INSERTED)

IF @.TableName = 'SyncTest-Deleteme'

BEGIN

DELETE FROM DownloadDataTypes WHERE [FileName] = 'SyncTest-DeleteMe'

END

ELSE

BEGIN

/*Inserting an IF/ELSE statement here dependant on @.FileType to seperate the handling of 'CAMPUS INVENTORY' file types.

IF @.FileType = 'CAMPUS INVENTORY'

BEGIN

DECLARE @.Qry varchar(4000)

--First, insert the record into tblSyncedInventory.

INSERT INTO tblSyncedInventory([FileName], FileType, CampusID, DateCreated)

SELECT [Filename], FileType, CampusID, DateDownloaded FROM INSERTED

SET @.ParentID = @.@.IDENTITY

--Now, go out and get the child records from their temp table, insert them into tblSyncedInventoryDetails, then drop the temp table.

SET @.Qry = 'INSERT INTO tblSyncedInventoryDetails (FileID, ISBN, Copies, Accession, DateCreated, FileName) SELECT ' + str(@.ParentID) + ', dbo.[' + @.TableName + '].ISBN, dbo.[' + @.TableName + '].Copies, NULL, GETDATE(), dbo.[' + @.TableName + '].FileName FROM dbo.[' + @.TableName + ']'

EXEC (@.Qry)

--Now, drop the temp table.

SET @.Qry = 'DROP TABLE [' + @.TableName + ']'

EXEC (@.Qry)

END

ELSE

BEGIN

INSERT INTO dbo.tblSyncedInventory([FileName],[FileType],[CampusID],[DateCreated]) VALUES (@.TableName, @.FileType, @.CampusID, @.DateCreated)

INSERT INTO tblDownloadDataTypes ([FileName], FileType, CampusID, DateCreated) SELECT [Filename], FileType, CampusID, DateDownloaded FROM INSERTED

SET @.ParentID = @.@.IDENTITY

EXEC stpro_ProcessPDAFileFromTrigger @.TableName, @.FileType, @.CampusID, @.ParentID

END

What error(s) are you receiving?

|||

I think you're missing one or more END statements. Each BEGIN should have a matching one

ALso, you can grab all the variables from INSERTED In one query:

SELECT @.TableName =[FileName],

@.FileName = [FileName],

@.FileType = FileType,

@.CampusID = CampusID,

@.DateCreated = DateDownLoaded

FROM INSERTED

Not sure about how temporary these temp tables are either, but without knowing the app or the rest of the code its difficult to suggest anything constructive.

HTH

sql

Create schema if not exists - problems

Hi,
I have a problem executing this statement on sqlserver2005:[vbcol=seagreen]
if not exists(select 1 from information_schema.schemata where
schema_name='testtest')
create schema TestTest AUTHORIZATION testuser;
go
<<<
I get a "Incorrect syntax near the keyword 'schema'", so what am i missing?!
TIA, Troy
Troy,
CREATE SCHEMA must be the first statement in a batch, but the IF is the
first statement, so the CREATE SCHEMA fails. (Yes, I agree with what you
are thinking about that.)
Here is a workaround, which is a simple bit of dynamic SQL:
if not exists(select 1 from information_schema.schemata where
schema_name='testtest')
EXEC ('create schema TestTest AUTHORIZATION testuser');
go
RLF
"Troy" <Troy@.discussions.microsoft.com> wrote in message
news:14E88836-6CD9-4A9D-ACBF-FB7EAF5502F3@.microsoft.com...
> Hi,
> I have a problem executing this statement on sqlserver2005:
> if not exists(select 1 from information_schema.schemata where
> schema_name='testtest')
> create schema TestTest AUTHORIZATION testuser;
> go
> <<<
> I get a "Incorrect syntax near the keyword 'schema'", so what am i
> missing?!
> TIA, Troy
|||Worked like a charm - Thanks
"Russell Fields" wrote:

> Troy,
> CREATE SCHEMA must be the first statement in a batch, but the IF is the
> first statement, so the CREATE SCHEMA fails. (Yes, I agree with what you
> are thinking about that.)
> Here is a workaround, which is a simple bit of dynamic SQL:
> if not exists(select 1 from information_schema.schemata where
> schema_name='testtest')
> EXEC ('create schema TestTest AUTHORIZATION testuser');
> go
> RLF
> "Troy" <Troy@.discussions.microsoft.com> wrote in message
> news:14E88836-6CD9-4A9D-ACBF-FB7EAF5502F3@.microsoft.com...
>
>

Create schema if not exists - problems

Hi,
I have a problem executing this statement on sqlserver2005:
>>
if not exists(select 1 from information_schema.schemata where
schema_name='testtest')
create schema TestTest AUTHORIZATION testuser;
go
<<<
I get a "Incorrect syntax near the keyword 'schema'", so what am i missing?!
TIA, TroyTroy,
CREATE SCHEMA must be the first statement in a batch, but the IF is the
first statement, so the CREATE SCHEMA fails. (Yes, I agree with what you
are thinking about that.)
Here is a workaround, which is a simple bit of dynamic SQL:
if not exists(select 1 from information_schema.schemata where
schema_name='testtest')
EXEC ('create schema TestTest AUTHORIZATION testuser');
go
RLF
"Troy" <Troy@.discussions.microsoft.com> wrote in message
news:14E88836-6CD9-4A9D-ACBF-FB7EAF5502F3@.microsoft.com...
> Hi,
> I have a problem executing this statement on sqlserver2005:
> if not exists(select 1 from information_schema.schemata where
> schema_name='testtest')
> create schema TestTest AUTHORIZATION testuser;
> go
> <<<
> I get a "Incorrect syntax near the keyword 'schema'", so what am i
> missing?!
> TIA, Troy|||Worked like a charm - Thanks :)
"Russell Fields" wrote:
> Troy,
> CREATE SCHEMA must be the first statement in a batch, but the IF is the
> first statement, so the CREATE SCHEMA fails. (Yes, I agree with what you
> are thinking about that.)
> Here is a workaround, which is a simple bit of dynamic SQL:
> if not exists(select 1 from information_schema.schemata where
> schema_name='testtest')
> EXEC ('create schema TestTest AUTHORIZATION testuser');
> go
> RLF
> "Troy" <Troy@.discussions.microsoft.com> wrote in message
> news:14E88836-6CD9-4A9D-ACBF-FB7EAF5502F3@.microsoft.com...
> > Hi,
> >
> > I have a problem executing this statement on sqlserver2005:
> >>
> > if not exists(select 1 from information_schema.schemata where
> > schema_name='testtest')
> > create schema TestTest AUTHORIZATION testuser;
> > go
> > <<<
> >
> > I get a "Incorrect syntax near the keyword 'schema'", so what am i
> > missing?!
> >
> > TIA, Troy
>
>sql

CREATE SCHEMA fails Inside an If Block

Hello All,

The below "CREATE SCHEMA" sql statement fails if it is inside an IF block. It runs fine if i run it without the IF block...

IF NOT EXISTS (SELECT * FROM sys.schemas WHERE name = N'Customer')

BEGIN

CREATE SCHEMA Customer AUTHORIZATION [sys]

END

-

Did anyone encountered this issue before....

Thanks..

Make this as dynamic SQL.|||

Thanks, Bushan.

As the DDL scripts can grow bigger, I feel that it is hard to maintain dynamic sql. But, I was just trying to figure out why this is not possible in this "create schema" scenario alone. It even works for "drop schema".

|||

Like the error message you get back says, CREATE SCHEMA must be the first command in the batch. So to do a CREATE SCHEMA in a script like this, that one statement has to be done dynamically.

IF NOT EXISTS (SELECT * FROM sys.schemas WHERE name = N'Customer')
BEGIN
exec ('CREATE SCHEMA Customer AUTHORIZATION [sys]')
END
Annoying? Yes? But it is not that much more work than doing it in the way that you (and I) originally expected :)

|||This is such an OBVIOUS shortcoming of TransactSQL. Why hasn't Microsoft corrected this flaw. As far as I know (with the exception of entering the exec ('sneak the CREATE in as a text string') there is no way to conditionally create a SCHEMA or a FUNCTION for that matter.

If it's disallowed for security reasons then why can we sneak it in with an EXEC?

The problem this causes for me (over and over again) is I write a sample function for the user and include it in my upgrade script. If they've already run the script for an earlier version, they already have my example and may have customized it to their specific application. If they have, I don't really want to replace it with my example again. So I'm stuck sneaking it in through the string route. This has been a flaw in T-SQL for a long time....

Sorry for the rant... Sure wish the T-SQL gods were listening |||
Thanks for the clarification..

Wednesday, March 7, 2012

Create Multiple Store Procedures in 1 SQL statement

Hi guys , may I know is that possible to create multiple store procedures in 1 time using 1 SQL statement? Thx for the assistance.

Best Regards,

Hans

I can't get your Question..

Need more information

|||

I hope you need to write sp like this way.

/*
sp1
*/
CREATE PROC MultipleStoreProcedures;1
AS
BEGIN
SELECT [CategoryID], [CategoryName], [Description], [Picture]
FROM [Northwind].[dbo].[Categories]
END

GO

/*
sp2
*/
CREATE PROC MultipleStoreProcedures;2
AS
BEGIN
SELECT [CustomerID], [CompanyName], [ContactName], [ContactTitle], [Address], [City], [Region], [PostalCode], [Country], [Phone], [Fax]
FROM [Northwind].[dbo].[Customers]
END
GO

**
--execute sp1
exec MultipleStoreProcedures;1
--execute sp2
exec MultipleStoreProcedures;2
**

|||

thx. it helps. :) However, if using 2005 for creating, then the 'GO' statement will be dissappear when u modify the store procedure. But it seems ok anyway. Thx alot.

Best Regards,

Hans

|||

The 'GO' isn't part of a T-SQL statement, it's just a marker that identifies where the end of batch is.
So, the above is, if you save it all as one file, and run it all at the same time, still two batches ( or statements if you will ), but it looks like it's working for you wanted anyway =:o)

/Kenneth

Saturday, February 25, 2012

Create indexes for Query Optimization

I am using ASP.net application on SQL server 2005.
I am getting data from the DB using this SQL statement from 2 tables:
Select Table1.a,Table1.b,Table2.C from Table1 INNER JOIN Table1 ON
Table2.e=Table.e Where Table1.a=XXX AND Table1.b>YYY Order Table1.a DESC
Table1 has around 2,000,000 Records and table has 3 records.
The query is running very slow.
How do Optimize the query using Indexes ?
On Which fields should I create the indexes ?
Thanks
ra294
ra294@.hotmail.com
On Jan 7, 6:56Xpm, "ra294" <ra...@.hotmail.com> wrote:
> I am using ASP.net application on SQL server 2005.
> I am getting data from the DB using this SQL statement from 2 tables:
> Select Table1.a,Table1.b,Table2.C from Table1 INNER JOIN Table1 ON
> Table2.e=Table.e Where Table1.a=XXX AND Table1.b>YYY Order Table1.a DESC
> Table1 has around 2,000,000 Records and table has 3 records.
> The query is running very slow.
> How do Optimize the query using Indexes ?
> On Which fields should I create the indexes X?
> Thanks
> ra294
> ra...@.hotmail.com
Do you have index on either columns a or b? Also, you might consider
remove the order by clause and do it later.

Create indexes for Query Optimization

I am using ASP.net application on SQL server 2005.
I am getting data from the DB using this SQL statement from 2 tables:
Select Table1.a,Table1.b,Table2.C from Table1 INNER JOIN Table1 ON
Table2.e=Table.e Where Table1.a=XXX AND Table1.b>YYY Order Table1.a DESC
Table1 has around 2,000,000 Records and table has 3 records.
The query is running very slow.
How do Optimize the query using Indexes ?
On Which fields should I create the indexes ?
Thanks
ra294
ra294@.hotmail.comra294 wrote:
> I am using ASP.net application on SQL server 2005.
> I am getting data from the DB using this SQL statement from 2 tables:
> Select Table1.a,Table1.b,Table2.C from Table1 INNER JOIN Table1 ON
> Table2.e=Table.e Where Table1.a=XXX AND Table1.b>YYY Order Table1.a DESC
> Table1 has around 2,000,000 Records and table has 3 records.
> The query is running very slow.
> How do Optimize the query using Indexes ?
> On Which fields should I create the indexes ?
> Thanks
> ra294
> ra294@.hotmail.com
>
>
try using database engine tuning advisor, find it in tools menu of the
management studio|||Without looking at the data Im just guessing but try doing this:
Table1 index: Key columns: a,b,e
Table2 index: key columns: e included: c
MC
"ra294" <ra294@.hotmail.com> wrote in message
news:uTLstxSUIHA.5404@.TK2MSFTNGP03.phx.gbl...
>I am using ASP.net application on SQL server 2005.
> I am getting data from the DB using this SQL statement from 2 tables:
> Select Table1.a,Table1.b,Table2.C from Table1 INNER JOIN Table1 ON
> Table2.e=Table.e Where Table1.a=XXX AND Table1.b>YYY Order Table1.a DESC
> Table1 has around 2,000,000 Records and table has 3 records.
> The query is running very slow.
> How do Optimize the query using Indexes ?
> On Which fields should I create the indexes ?
> Thanks
> ra294
> ra294@.hotmail.com
>
>|||ra294,
You might want to recheck your posting. The query is not valid (because
of typos?), and the number of rows are suspect (really just 3 rows in
one table and 2 million rows in the other table?).
How many rows does the query return? 3? 6 million? How big is the table
with the 2 million rows (how many pages or how much MB)?
How slow is the query currently? 200 milliseconds, 5 seconds, 5 minutes?
In general, you should always define a Primary Key for each table. This
will automatically create a corresponding unique index. You should also
define any Foreign Key relations. In general, it is a good idea to index
Foreign Key relations.
If you would like more assistence, then please post simplified DDL (and
the answers to the questions above).
--
Gert-jan
ra294 wrote:
> I am using ASP.net application on SQL server 2005.
> I am getting data from the DB using this SQL statement from 2 tables:
> Select Table1.a,Table1.b,Table2.C from Table1 INNER JOIN Table1 ON
> Table2.e=Table.e Where Table1.a=XXX AND Table1.b>YYY Order Table1.a DESC
> Table1 has around 2,000,000 Records and table has 3 records.
> The query is running very slow.
> How do Optimize the query using Indexes ?
> On Which fields should I create the indexes ?
> Thanks
> ra294
> ra294@.hotmail.com|||On Jan 7, 6:56=A0pm, "ra294" <ra...@.hotmail.com> wrote:
> I am using ASP.net application on SQL server 2005.
> I am getting data from the DB using this SQL statement from 2 tables:
> Select Table1.a,Table1.b,Table2.C from Table1 INNER JOIN Table1 ON
> Table2.e=3DTable.e Where Table1.a=3DXXX AND Table1.b>YYY Order Table1.a DE=SC
> Table1 has around 2,000,000 Records and table has 3 records.
> The query is running very slow.
> How do Optimize the query using Indexes ?
> On Which fields should I create the indexes =A0?
> Thanks
> ra294
> ra...@.hotmail.com
Do you have index on either columns a or b? Also, you might consider
remove the order by clause and do it later.

Create INDEX within CREATE TABLE DDL

Hi

Minor and inconsequential but sometimes you just gotta know:

Is it possible to define a non-primary key index within a Create Table statement? I can create a constraint and a PK. I can create the table and then add the index. I just wondered if you can do it in one statement.

e.g. I have:

CREATE TABLE MyT
(MyT_ID INT Identity(1, 1) CONSTRAINT MyT_PK PRIMARY KEY Clustered,
MyT_Desc Char(40) NOT NULL CONSTRAINT MyT_idx1 UNIQUE NONCLUSTERED ON [DEFAULT])
which creates a table with a PK and unique constraint.
I would like (pseudo SQL):
CREATE TABLE MyT
(MyT_ID INT Identity(1, 1) CONSTRAINT MyT_PK PRIMARY KEY Clustered,
MyT_Desc Char(40) NOT NULL CONSTRAINT MyT_idx1 UNIQUE INDEX NONCLUSTERED ON [DEFAULT])

No big deal - just curious :D Once I know I can stop scouring BOL for clues.

Tks in advanceI don't think so. I don't recall seeing any syntax that allows this. Non-clustered indexes are separate objects from the table, and that is probably why they need to be created separately, and can be dropped separately as well.|||I don't think so. I don't recall seeing any syntax that allows this. Non-clustered indexes are separate objects from the table, and that is probably why they need to be created separately, and can be dropped separately as well.
Cheers BM - didn't think of it like that - that does kind of make sense - you can't create an object dependent on another object before the first object exists. Or something similar but more felicitous ;)

'CREATE INDEX' Statement...Faster?

I am indexing a 32 millon row table with a unqine clustered index and
the run time for the create index statement is over 4 hours long. This
runs is too slow and may cost me a job If i cant find a faster way to
create index on large table.
Can anyone help.
Hi
What is the version of SQL Server?
<GreenHillCourt@.gmail.com> wrote in message
news:a7661fdd-12e9-4a12-969f-6ec961eab992@.n1g2000prb.googlegroups.com...
>I am indexing a 32 millon row table with a unqine clustered index and
> the run time for the create index statement is over 4 hours long. This
> runs is too slow and may cost me a job If i cant find a faster way to
> create index on large table.
> Can anyone help.
|||i don't think it would be faster. Clustered Index is the way data is stored
physically in the hard disk.
bye!
"GreenHillCourt@.gmail.com" wrote:

> I am indexing a 32 millon row table with a unqine clustered index and
> the run time for the create index statement is over 4 hours long. This
> runs is too slow and may cost me a job If i cant find a faster way to
> create index on large table.
> Can anyone help.
>
|||Setting the database to simple recovery should improve compared to full recovery. At least it will
cut down on the logging. But the data shuffling still has to occur of course...
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://sqlblog.com/blogs/tibor_karaszi
"DarthSidious" <DarthSidious@.discussions.microsoft.com> wrote in message
news:15C6F565-D67E-4912-8424-BFBDF0EC88A2@.microsoft.com...[vbcol=seagreen]
>i don't think it would be faster. Clustered Index is the way data is stored
> physically in the hard disk.
> bye!
> "GreenHillCourt@.gmail.com" wrote:
|||<GreenHillCourt@.gmail.com> wrote in message
news:a7661fdd-12e9-4a12-969f-6ec961eab992@.n1g2000prb.googlegroups.com...
>I am indexing a 32 millon row table with a unqine clustered index and
> the run time for the create index statement is over 4 hours long. This
> runs is too slow and may cost me a job If i cant find a faster way to
> create index on large table.
As others have said, if you're creating the clustered index, not much you
can do other than perhaps look at a faster disk subsystem (say raid 10 vs
RAID 5, etc.)
If you mean you're creating a non-clustered index on a table that has an
existing clustered index, one thing that can certainly help is putting the
non-clustered index on its own set of disks.

> Can anyone help.
Greg Moore
SQL Server DBA Consulting Remote and Onsite available!
Email: sql (at) greenms.com http://www.greenms.com/sqlserver.html
|||Have you tried creating the index without clustering? If I'm not mistaken,
it should then not have to physically re-order the data.
<GreenHillCourt@.gmail.com> wrote in message
news:a7661fdd-12e9-4a12-969f-6ec961eab992@.n1g2000prb.googlegroups.com...
>I am indexing a 32 millon row table with a unqine clustered index and
> the run time for the create index statement is over 4 hours long. This
> runs is too slow and may cost me a job If i cant find a faster way to
> create index on large table.
> Can anyone help.
|||"GreenHillCourt@.gmail.com" wrote:
> I am indexing a 32 millon row table with a unqine clustered index and
> the run time for the create index statement is over 4 hours long. This
> runs is too slow and may cost me a job If i cant find a faster way to
> create index on large table.
> Can anyone help.
- drop all unnecessary nonclustered indexes
- if possible, connect in single user mode
- add extra memory to the server, don't "pin" tables
- make sure you have enough I/O and bandwidth, both for your table, the
TempDB and the log file
- make sure you have enough free space before you start, at least 1.5
times the table size
- set the database recovery mode to simple
- choose an appropriate fillfactor. Any value below 70 is probably a bad
idea
4 hours seems excessive. How much space does the table occupy (before
you start)? What is your I/O system (number of disks, etc.)?
Gert-Jan
SQL Server MVP

'CREATE INDEX' Statement...Faster?

I am indexing a 32 millon row table with a unqine clustered index and
the run time for the create index statement is over 4 hours long. This
runs is too slow and may cost me a job If i cant find a faster way to
create index on large table.
Can anyone help.Hi
What is the version of SQL Server?
<GreenHillCourt@.gmail.com> wrote in message
news:a7661fdd-12e9-4a12-969f-6ec961eab992@.n1g2000prb.googlegroups.com...
>I am indexing a 32 millon row table with a unqine clustered index and
> the run time for the create index statement is over 4 hours long. This
> runs is too slow and may cost me a job If i cant find a faster way to
> create index on large table.
> Can anyone help.|||i don't think it would be faster. Clustered Index is the way data is stored
physically in the hard disk.
bye!
"GreenHillCourt@.gmail.com" wrote:
> I am indexing a 32 millon row table with a unqine clustered index and
> the run time for the create index statement is over 4 hours long. This
> runs is too slow and may cost me a job If i cant find a faster way to
> create index on large table.
> Can anyone help.
>|||Setting the database to simple recovery should improve compared to full recovery. At least it will
cut down on the logging. But the data shuffling still has to occur of course...
--
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://sqlblog.com/blogs/tibor_karaszi
"DarthSidious" <DarthSidious@.discussions.microsoft.com> wrote in message
news:15C6F565-D67E-4912-8424-BFBDF0EC88A2@.microsoft.com...
>i don't think it would be faster. Clustered Index is the way data is stored
> physically in the hard disk.
> bye!
> "GreenHillCourt@.gmail.com" wrote:
>> I am indexing a 32 millon row table with a unqine clustered index and
>> the run time for the create index statement is over 4 hours long. This
>> runs is too slow and may cost me a job If i cant find a faster way to
>> create index on large table.
>> Can anyone help.|||<GreenHillCourt@.gmail.com> wrote in message
news:a7661fdd-12e9-4a12-969f-6ec961eab992@.n1g2000prb.googlegroups.com...
>I am indexing a 32 millon row table with a unqine clustered index and
> the run time for the create index statement is over 4 hours long. This
> runs is too slow and may cost me a job If i cant find a faster way to
> create index on large table.
As others have said, if you're creating the clustered index, not much you
can do other than perhaps look at a faster disk subsystem (say raid 10 vs
RAID 5, etc.)
If you mean you're creating a non-clustered index on a table that has an
existing clustered index, one thing that can certainly help is putting the
non-clustered index on its own set of disks.
> Can anyone help.
Greg Moore
SQL Server DBA Consulting Remote and Onsite available!
Email: sql (at) greenms.com http://www.greenms.com/sqlserver.html|||Have you tried creating the index without clustering? If I'm not mistaken,
it should then not have to physically re-order the data.
<GreenHillCourt@.gmail.com> wrote in message
news:a7661fdd-12e9-4a12-969f-6ec961eab992@.n1g2000prb.googlegroups.com...
>I am indexing a 32 millon row table with a unqine clustered index and
> the run time for the create index statement is over 4 hours long. This
> runs is too slow and may cost me a job If i cant find a faster way to
> create index on large table.
> Can anyone help.|||"GreenHillCourt@.gmail.com" wrote:
> I am indexing a 32 millon row table with a unqine clustered index and
> the run time for the create index statement is over 4 hours long. This
> runs is too slow and may cost me a job If i cant find a faster way to
> create index on large table.
> Can anyone help.
- drop all unnecessary nonclustered indexes
- if possible, connect in single user mode
- add extra memory to the server, don't "pin" tables
- make sure you have enough I/O and bandwidth, both for your table, the
TempDB and the log file
- make sure you have enough free space before you start, at least 1.5
times the table size
- set the database recovery mode to simple
- choose an appropriate fillfactor. Any value below 70 is probably a bad
idea
4 hours seems excessive. How much space does the table occupy (before
you start)? What is your I/O system (number of disks, etc.)?
--
Gert-Jan
SQL Server MVP

CREATE INDEX statement for SQL Mobile not documented?

Hello,

I'm unable to find documentation for the CREATE INDEX statement for SQL Mobile. DROP INDEX is documented however. Is this a known issue or am I missing something? This can be seen here:

http://msdn2.microsoft.com/en-us/library/ms173440(en-US,SQL.90).aspx

If you scroll the left pane up a little, you will notice that CREATE INDEX is not in the tree. Am I missing something?

Thanks.Thanks Ravi for catching this. And we are aware of it too.
We already have a bug opened in our Bug Database for this.

The next web site refresh should pickup the fix.

Thanks,
Laxmi NRO, MSFT, SQL Mobile, Microsoft Corporation|||Yes, the topic will be available in the December download version of SQL Server Books Online.

In the meantime, you can use the CREATE INDEX topic in the full version of Books Online : http://msdn2.microsoft.com/en-us/library/ms188783(en-US,SQL.90).aspx

Regards,|||

Finally it is live in SQL Mobile Books Online @. http://msdn2.microsoft.com/en-us/library/ms345331(en-US,SQL.90).aspx

Thanks,.

Laxmi Narsimha Rao ORUGANTI, MSFT, SQL Mobile, Microsoft Corporation

CREATE INDEX statement for SQL Mobile not documented?

Hello,

I'm unable to find documentation for the CREATE INDEX statement for SQL Mobile. DROP INDEX is documented however. Is this a known issue or am I missing something? This can be seen here:

http://msdn2.microsoft.com/en-us/library/ms173440(en-US,SQL.90).aspx

If you scroll the left pane up a little, you will notice that CREATE INDEX is not in the tree. Am I missing something?

Thanks.Thanks Ravi for catching this. And we are aware of it too.
We already have a bug opened in our Bug Database for this.

The next web site refresh should pickup the fix.

Thanks,
Laxmi NRO, MSFT, SQL Mobile, Microsoft Corporation|||Yes, the topic will be available in the December download version of SQL Server Books Online.

In the meantime, you can use the CREATE INDEX topic in the full version of Books Online : http://msdn2.microsoft.com/en-us/library/ms188783(en-US,SQL.90).aspx

Regards,|||

Finally it is live in SQL Mobile Books Online @. http://msdn2.microsoft.com/en-us/library/ms345331(en-US,SQL.90).aspx

Thanks,.

Laxmi Narsimha Rao ORUGANTI, MSFT, SQL Mobile, Microsoft Corporation

Sunday, February 19, 2012

Create Error Message and Abort

I would like to place the sql statement listed below in a SQL Server
Enterprise Manager job if this is true abort the job and send message.
If (select value from salary) < 10
Error Message 'Salary Less Than 10'
Joe,
Are you trying to create a user-defined error message and invoke it in code?
If so use sp_addmessage and the T-SQL RAISERROR statment. See SQL BOL for
more details.
HTH
Jerry
"Joe K." <Joe K.@.discussions.microsoft.com> wrote in message
news:9BB22A3F-2617-4A06-A23E-F216250850AF@.microsoft.com...
>
> I would like to place the sql statement listed below in a SQL Server
> Enterprise Manager job if this is true abort the job and send message.
> If (select value from salary) < 10
> Error Message 'Salary Less Than 10'
>