snipt

Ctrl+h for KB shortcuts

Text only

SQL dynamic field return with sp_executesql

1
2
3
4
5
Given @fieldlist is a parameter with comma separated fieldnames:

declare @sql  varchar(4000)
select @sql = ‘select ‘ + @fieldlist + ‘ from mytable’
exec sp_executesql @sql
https://snipt.net/embed/30a33bd9cd200c4fbd8c840002f457ec/
/raw/30a33bd9cd200c4fbd8c840002f457ec/
30a33bd9cd200c4fbd8c840002f457ec
text
Text only
5
2019-08-06T13:08:17
True
False
False
/api/public/snipt/41431/
sql-dynamic-field-return-with-sp_executesql
<table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre><a href="#L-1">1</a> <a href="#L-2">2</a> <a href="#L-3">3</a> <a href="#L-4">4</a> <a href="#L-5">5</a></pre></div></td><td class="code"><div class="highlight"><pre><span></span><span id="L-1"><a name="L-1"></a>Given @fieldlist is a parameter with comma separated fieldnames: </span><span id="L-2"><a name="L-2"></a> </span><span id="L-3"><a name="L-3"></a>declare @sql varchar(4000) </span><span id="L-4"><a name="L-4"></a>select @sql = ‘select ‘ + @fieldlist + ‘ from mytable’ </span><span id="L-5"><a name="L-5"></a>exec sp_executesql @sql </span></pre></div> </td></tr></table>
SQL, stored-procedure