Nếu bạn cần phải nhận được kịch bản từ T-SQL sau đó chỉ sử dụng xp_cmdshell. Ví dụ kịch bản chỉ số concreate của xem concreate với SMO và PowerShell (kết quả là trong biến @script, bạn có thể thực hiện nó với 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',''''[email protected]+'''')
SET @ps=REPLACE(@ps,'$ln',''''[email protected]+'''')
SET @ps=REPLACE(@ps,'$pw',''''[email protected]+'''')
SET @ps=REPLACE(@ps,'$db',''''[email protected]+'''')
SET @ps=REPLACE(@ps,'$schemaName',''''[email protected]+'''')
SET @ps=REPLACE(@ps,'$viewName',''''[email protected]+'''')
SET @ps=REPLACE(@ps,'$indexName',''''[email protected]+'''')
SET @cmd = 'powershell -Command "'[email protected][email protected]+'"'
exec dev.Msg @cmd
INSERT INTO @OUTPUT
exec xp_cmdshell @cmd
SELECT @script+line FROM @OUTPUT
WHERE line is not null
PRINT @script
T.B. Đối với những người hỏi lý do tại sao chúng tôi có thể cần các thủ thuật như vậy: trong một số trường hợp, ví dụ: "nhập dữ liệu bằng công cụ của bên thứ ba", cách tiếp cận "thả lại" hoạt động tốt hơn các đối tượng "bật tắt", ví dụ: vì công cụ của bên thứ ba có thể gọi là "cắt bớt" và nếu bảng của bạn tham gia chế độ xem lược đồ, bạn sẽ gặp lỗi công cụ của bên thứ ba (bảng cắt bớt tham gia vào các chế độ xem được lập chỉ mục sẽ phát sinh lỗi, do đó chúng tôi buộc phải bỏ chế độ xem với tất cả các chỉ mục trước khi nhập và tạo lại sau).
Nguồn
2014-01-29 14:19:52
Tôi muốn thực hiện việc này từ tập lệnh. Trong Mysql tôi sẽ làm "show create table exampletablename" cho mỗi bảng. – tomsv