I have an awesome query that populates my virtual table with a list of scripts that create non clustered indices for all foreign keys.
However this list is great but, I want to take it another step further and run a dynamic query to execute each script.
I don't really have that much exp with dynamic query's as most time I simply replicate functionality in my c# software instead.
So I have..
DECLARE @SQLquery as NVARCHAR(MAX)
SET @SQLquery = (SELECT * FROM #ForiegnKeyScriptsNumero)
EXECUTE @SQLquery
DROP TABLE #ForiegnKeyScriptsNumero
now this is not going to work as im returning mulitple rows.
What I need to do is to simply get each row and execute one after the other.
For the life of me my brain has had a melt down and I just cannot see it.
I know this is a simple fix, what am I missing?
UPDATE ::
Just to add here's what my script generates in each row of my table, table has just 1 column.
IF NOT EXISTS
(SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[ActivityLog]')
AND name = N'IX_ActivityLogTypeId') CREATE NONCLUSTERED INDEX [IX_ActivityLogTypeId] ON [dbo].[ActivityLog]( [ActivityLogTypeId] ASC )
WITH (PAD_INDEX = OFF,
STATISTICS_NORECOMPUTE = OFF,
SORT_IN_TEMPDB = OFF,
IGNORE_DUP_KEY = OFF,
DROP_EXISTING = OFF,
ONLINE = OFF,
ALLOW_ROW_LOCKS = ON,
ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
This code is what is in my rows.
As a treat I thought I would post this script that generates the scripts.
CREATE TABLE #ForiegnKeyScriptsRun (scripts nvarchar(max))
INSERT INTO #ForiegnKeyScriptsRun
SELECT
'IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N''[dbo].['
+ tab.[name]
+ ']'') AND name = N''IX_'
+ cols.[name]
+ ''') '
+ 'CREATE NONCLUSTERED INDEX [IX_'
+ cols.[name]
+ '] ON [dbo].['
+ tab.[name]
+ ']( ['
+ cols.[name]
+ '] ASC ) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]'
FROM
sys.foreign_keys keys
INNER JOIN
sys.foreign_key_columns keyCols
ON keys.object_id = keyCols.constraint_object_id
INNER JOIN
sys.columns cols
ON keyCols.parent_object_id = cols.object_id
AND
keyCols.parent_column_id = cols.column_id
INNER JOIN
sys.tables tab
ON keyCols.parent_object_id = tab.object_id
ORDER BY tab.[name], cols.[name]
OK, I followed JKN solution but the generated code when checked does not like IF
EXEC IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[ActivityLog]') AND name = N'IX_ActivityLogTypeId') CREATE NONCLUSTERED INDEX [IX_ActivityLogTypeId] ON [dbo].[ActivityLog]( [ActivityLogTypeId] ASC ) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
the error is "Incorrect syntax near the keyword 'IF'." Again I am not sure what syntax is needed for dynamic sql, is there some syntax missing? Can anyone spot this?