If you need to get a script from T-SQL, then only using xp_cmdshell. For example, the concreate scripting index to represent Concreate with SMO and powershell (the result is in the @ script variable, you can execute it with sp_executesql):
DECLARE @OUTPUT TABLE (line nvarchar(max)) DECLARE @cmd VARCHAR(8000), @ps VARCHAR(8000), @psLoadAssemblies VARCHAR(8000), @script nvarchar(max) ='' DECLARE @srv nvarchar(max)='<server name>', @ln nvarchar(max)='<login>', @pw nvarchar(max)='<password>', @db nvarchar(max) = '<database>', @schemaName nvarchar(max) = '<schema>', -- without '[' ']' @viewName nvarchar(max) = '<view name>', -- without '[' ']' @indexName nvarchar(max) = '<index name>' -- without '[' ']' SET @psLoadAssemblies = '[System.Reflection.Assembly]::LoadWithPartialName(''Microsoft.SqlServer.SMO'')|Out-Null;' SET @ps='$using=''Microsoft.SqlServer.Management.Smo'';$s=new-object($using+''.Server'') $srv;$c = $s.ConnectionContext;$c.LoginSecure=$false;$c.Login=$ln;$c.Password=$pw; Write-Host ($s.Databases[$db].Views.Item($viewName,$schemaName).Indexes[$indexName].Script())' SET @ps=REPLACE(@ps,'$srv','''' +@srv +'''') SET @ps=REPLACE(@ps,'$ln','''' +@ln +'''') SET @ps=REPLACE(@ps,'$pw','''' +@pw +'''') SET @ps=REPLACE(@ps,'$db','''' +@db +'''') SET @ps=REPLACE(@ps,'$schemaName','''' +@schemaName +'''') SET @ps=REPLACE(@ps,'$viewName','''' +@viewName +'''') SET @ps=REPLACE(@ps,'$indexName','''' +@indexName +'''') SET @cmd = 'powershell -Command "' +@psLoadAssemblies +@ps +'"' exec dev.Msg @cmd INSERT INTO @OUTPUT exec xp_cmdshell @cmd SELECT @script+line FROM @OUTPUT WHERE line is not null PRINT @script
PS For those who ask why we need such tricks: in some scenarios, for example. “data import using a third-party tool”, the drop-recreate approach works better than enable-disable objects, for example. because such a third-party tool can cause “crop”, and if your table participates in a schema-bound view, you will get a third-party tool error (a truncating table participating in indexed views throws an error, so we are forced to discard the view with all indices before importing and recreate it after).
Roman pokrovskij
source share