2016-03-31 5 views
2
declare @tags1 varchar(max) 
declare @blockcount int 
declare @blockstring varchar(max) 
set @tags1='%Gifts%' Or CategoryTag Like'%Packaging%' 
set @blockstring= 'SELECT @blogcount=count(*) FROM M_PHBLogs where CategoryTag LIKE '+ @tags1 +' AND ContentType=1 ' 
exec (@blockstring) 

ich sp_executesql das Ergebnis von exec (@blockstring) in eine andere Variable wieWie Wert der Variablen auf 'exec' in SQL mit

@blockcount=exec(@blockstring) 
if(@blockcount!=0) 
BEGIN 
    //something 
END 
+0

Mögliche Duplikat von [Wie ein exec Ergebnis einer SQL-Variablen zuweisen? ] (http://stackoverflow.com/questions/2245691/how-to-assign-an-exec-result-to-a-sql-variable) – HoneyBadger

+3

Mögliches Duplikat von [Wie bekomme ich sp \ _executesql result in eine Variable? ] (http://stackoverflow.com/questions/803211/how-to-get-sp-executesql-result-into-a-variable) –

Antwort

0

Verwendung speichern möchten. Eigentlich sollten Sie diese Funktion immer verwenden, da sie die Parametrierung ermöglicht.

declare @tags1 varchar(max); 
declare @blockcount int; 
declare @blockstring varchar(max); 

set @tags1 = '''%Gifts%'' Or CategoryTag Like ''%Packaging%'''; 
set @blockstring= 'SELECT @blogcount = count(*) FROM M_PHBLogs where CategoryTag LIKE '+ @tags1 +' AND ContentType = 1'; 

exec sp_executesql @blockstring, N'@blockcount int output', @blockcount = @blockcount; 
+0

Variable @ tag1 wird falsch von OP zugewiesen. –

0

Verwenden sp_executesql Denken Sie daran, declare @blockstring nvarchar(max)

Nennen Sie es auf diese Weise:

exec sp_executesql @blockstring, N'@blogcount int output', @blogcount = @blockcount OUTPUT; 
select @blockcount 
0

nicht mit exec (soweit ich weiß), aber unter Verwendung von Sp_executesql Sie Parameter definieren und Übergeben Sie diese Parameter als Eingabe oder Ausgabe an das dynamisch erstellte SQL-Skript

Hier wird Version des SQL-Skript vereinfacht

declare @tags1 nvarchar(max) 
declare @blockcount int 
declare @blockstring nvarchar(max) 

declare @blogcount_out int; 
set @blockstring= 'SELECT @blogcount = count(*) FROM UserDocuments' 
EXECUTE sp_executesql @blockstring, N'@blogcount int output', @blogcount = @blogcount_out output 
select @blogcount_out 

Bitte lesen Sie die Anleitung Use sp_ExecuteSQL T-SQL Stored Procedure with Input and Output Parameters für detailliertere Proben, wie params zu verwenden, um mit Sp_executesql