Quantcast
Channel: Transact-SQL forum
Viewing all articles
Browse latest Browse all 23857

T-SQL Code Structure - Review/Comment?

$
0
0

Hello,

I'm still new to T-SQL and have hundreds of CHECK constraints that I need to create scripts for. I'm interested in comments from the more experienced folks out there as to the best way to structure my code.

See below and let me have it!

Thanks.

Bill

DECLARE @TABLENAME NVARCHAR(100)
DECLARE @CONSTNAME NVARCHAR(4000)
DECLARE @CONSTEXPR NVARCHAR(4000)

SET @TABLENAME = '[dbo].[csEvents]'

SET @CONSTNAME = '[Event description cannot be empty]'
SET @CONSTEXPR = '[ev_mevent]<>'''''

BEGIN TRY
	EXEC ('ALTER TABLE ' + @TABLENAME + ' DROP CONSTRAINT ' + @CONSTNAME)
END TRY
BEGIN CATCH
END CATCH

EXEC ('ALTER TABLE ' + @TABLENAME + ' WITH NOCHECK ADD CONSTRAINT ' + @CONSTNAME + ' CHECK (' + @CONSTEXPR + ')')
EXEC ('ALTER TABLE ' + @TABLENAME + ' CHECK CONSTRAINT ' + @CONSTNAME)

SET @CONSTNAME = '[Start datetime cannot be later than end datetime]'
SET @CONSTEXPR = '[ev_tdtstart]<=[ev_tdtend]'

BEGIN TRY
	EXEC ('ALTER TABLE ' + @TABLENAME + ' DROP CONSTRAINT ' + @CONSTNAME)
END TRY
BEGIN CATCH
END CATCH

EXEC ('ALTER TABLE ' + @TABLENAME + ' WITH NOCHECK ADD CONSTRAINT ' + @CONSTNAME + ' CHECK (' + @CONSTEXPR + ')')
EXEC ('ALTER TABLE ' + @TABLENAME + ' CHECK CONSTRAINT ' + @CONSTNAME)


Viewing all articles
Browse latest Browse all 23857

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>