1
我有一個令人敬畏的查詢,它使用爲所有外鍵創建非聚集索引的腳本列表填充我的虛擬表。如何從錶行執行SQL動態查詢字符串?
但是,這個列表是偉大的,但我想更進一步,並運行一個動態查詢來執行每個腳本。
我真的沒有那麼多的動態查詢exp,因爲大多數時候我只是在我的c#軟件中複製功能。
所以我..
DECLARE @SQLquery as NVARCHAR(MAX)
SET @SQLquery = (SELECT * FROM #ForiegnKeyScriptsNumero)
EXECUTE @SQLquery
DROP TABLE #ForiegnKeyScriptsNumero
現在這不會作爲即時通訊返回多張行工作。
我需要做的是簡單地獲取每一行並逐個執行。
對於我的生活,我的大腦已經融化,我看不到它。
我知道這是一個簡單的修復,我錯過了什麼?
更新::
就在這裏補充就是我的劇本我的表的每一行中產生,表中有僅有1列。
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]
這段代碼就是我的行。
作爲一種享受,我想我會發布這個腳本來生成腳本。
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,我也跟着JKN解決方案,但檢查時生成的代碼不一樣,如果
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]
錯誤是「關鍵字‘IF’附近有語法錯誤。」我再次不確定動態sql需要什麼語法,是否有一些語法丟失?任何人都可以看到嗎?
以及此刻我的FK腳本生成的SQL腳本的列表。 以幾乎相同的方式,我想我可以使用這個,並轉換我的腳本,所以它一次去做....好!!!! – lemunk
其返回null出於某種原因.... – lemunk
@StevenSmith如果你的任何行是NULL該表就會使整個事情空 – JNK