Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2005 Forums
 Transact-SQL (2005)
 Dodgy SQL 'IF Statement' Syntax

Author  Topic 

Dremandred
Starting Member

2 Posts

Posted - 2009-03-02 : 11:41:48
Hi all

I don't create SQL stored procedures very often and as a result I am suffering from lack of SQL syntax knowledge.

My procedure needs to check if table1 exists and drop it if it does and the create table1 again based on View1 However I'm battling with the conditional syntax here :)

The Troublesome Stored Procedure:

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Description: <If table exits drop it and create the new table based on the view.>
-- =============================================
CREATE PROCEDURE TableBasedOnView
AS
BEGIN
SET NOCOUNT ON;
IF (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME='table1') = true
DROP TABLE table1
END IF
--Create a table from view.
SELECT * INTO table1 FROM dbo.View1
END
GO


Any comments or assistance here would be greatly appreciated.

RickD
Slow But Sure Yak Herding Master

3608 Posts

Posted - 2009-03-02 : 11:56:03
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Description: <If table exits drop it and create the new table based on the view.>
-- =============================================
CREATE PROCEDURE TableBasedOnView
AS
BEGIN
SET NOCOUNT ON;
IF (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME='table1') = true DROP TABLE table1

--Create a table from view.
SELECT * INTO table1 FROM dbo.View1
END
GO
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2009-03-02 : 12:40:50
i prefer using
IF EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME='table1')
DROP TABLE table1

instead of

IF (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME='table1') = true
DROP TABLE table1
Go to Top of Page

Dremandred
Starting Member

2 Posts

Posted - 2009-03-03 : 04:14:08
Many, many thanks. I knew I was irritatingly close :)
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2009-03-03 : 09:36:21
welcome
Go to Top of Page

Michael Valentine Jones
Yak DBA Kernel (pronounced Colonel)

7020 Posts

Posted - 2009-03-03 : 09:45:45
This also works:
if object_id('dbo.table1','U') is not null drop table dbo.table1


CODO ERGO SUM
Go to Top of Page
   

- Advertisement -