sql server select rows into string - sql

I have the following query.
declare #column_names varchar(1000)
declare #result varchar(1000)
set #column_names='id,firstname,lastname,age,city,country'
set #result=''
select #result=#result+#column_names +','+from studenttable where id='1'
But this query returns id,firstname,lastname,age,city,country as result
and not like 1,john,j,21,newyork,us.
How to change query so that #result will contain actual entries in comma-separated form?
Please reply. Thanks.

To execute dynamic T-SQL statements use sp_executesql as:
EXECUTE sp_executesql
N'SELECT ' +#column_names +' FROM studenttable
WHERE id= #id',
N'#id tinyint',
#id= 1;

Related

How to SELECT INTO <a calculated table name>? [duplicate]

I have a problem with treating table name as variable as I need to put the results to different table each month automatically (without using any advanced procedures to make this query dynamic). Can somebody help me to modify this code and make it work?
declare #exp_dte as date;
set #exp_dte='2015-12-31';
print (#exp_dte);
declare #tab_mth as nvarchar(max);
set #tab_mth=year(#exp_dte)*100+month(#exp_dte);
print (#tab_mth);
declare #tab_name as nvarchar(max)
set #tab_name='mis_anl.dbo.BIK_' + #tab_mth
print (#tab_name);
IF OBJECT_ID (N'#tab_name', N'U') IS NOT NULL
begin
drop table #tab_name
end
select distinct
*
into #tab_name
from table_x
You have to use dynamic SQL to set name at runtime:
DECLARE #exp_dte DATE = '2015-12-31';
DECLARE #tab_name SYSNAME = '[dbo].' + QUOTENAME('BIK_' + FORMAT(#exp_dte, 'yyyyMM'));
IF OBJECT_ID (#tab_name, N'U') IS NOT NULL
BEGIN
EXEC('DROP TABLE' + #tab_name);
END
DECLARE #sql NVARCHAR(MAX) = N'SELECT DISTINCT *
INTO #tab_name
FROM table_x';
SET #sql = REPLACE(#sql, '#tab_name', #tab_name);
EXEC [dbo].[sp_executesql] #sql;
LiveDemo
Remarks:
Try to be more conscise
You could use FORMAT to get yyyyMM (SQL Server 2012+)
Always QUOTENAME generated identifiers to avoid SQL Injection attacks
I strongly recommend to read The Curse and Blessings of Dynamic SQL especially CREATE TABLE #tbl.
use dynamic sql ,you cant user table names as variables
declare #exp_dte as date;
set #exp_dte='2015-12-31';
declare #tab_mth as nvarchar(max);
set #tab_mth=year(#exp_dte)*100+month(#exp_dte);
declare #tab_name as nvarchar(max)
set #tab_name='mis_anl.dbo.BIK_' + #tab_mth
declare #sql1 nvarchar(max)
set #sql1='drop table '+#tab_name;
IF exists(select 1 from information_schema.tables where table_name=#tab_name)
begin
exec(#sql1);
end
declare #sql nvarchar(max)
set #sql='
select distinct
*
into '+#tab_name+'
from table_x'
exec (#sql)

How to pass table name dynamically to the stored procedure or a simple SQL query, then store the results in a variable?

How to pass table name dynamically to the stored procedure or a simple SQL query, then store the results in a variable?
You may looking for something like this ?
USE [master]
GO
DECLARE #sql NVARCHAR(2000)
DECLARE #TableName NVARCHAR(100) ='sys.tables'
DECLARE #RecordCount INT
SET #sql = N' SELECT #RecordCountOut = COUNT(*)
FROM ' + #TableName + ' AS t'
EXEC sp_executesql #sql, N'#RecordCountOut INT OUTPUT', #RecordCountOut = #RecordCount OUTPUT
SELECT #RecordCount
You could stored your SQL query result in this way
DECLARE #Result NVARCHAR(MAX)
SELECT #Result = COLUMN FROM TableName
however, you could use print command to check what the query return
print #Result

Dynamic SQL Result INTO #Temp Table

I have to Execute a dynamic SQL SELECT Query And put Results into a #TempTable.
DECLARE #StateId CHAR(3)='StateID';
DECLARE #DeptId CHAR(15)='DeptID';
DECLARE #Query VARCHAR(MAX)='Select Columns With Joins Passed From Front End'
DECLARE #Where VARCHAR(500);
DECLARE #FinalQuery VARCHAR(MAX)='';
SET #Where='Some Where Condition';
SET #FinalQuery='SELECT '+#Query+' '+#Where+''
EXEC(#FinalQuery) -- Want To INSERT THIS Result IN SOME `#TempTable`
-- SO that I can perform Some Operations On `#TempTable`
ALSO No Of columns returned From Dynamic SQL SELECT Are Dynamic.
Thanks,
try the below example
DECLARE #StateId CHAR(3)='StateID';
DECLARE #DeptId CHAR(15)='DeptID';
DECLARE #Query VARCHAR(MAX)='*' -- here you pass your query
DECLARE #Where VARCHAR(500);
DECLARE #FinalQuery VARCHAR(MAX)='';
SET #Where='from tablename where condition';
SET #FinalQuery='SELECT '+#Query+' INTO #temptablename '+#Where;
EXEC(#FinalQuery)
Note
:If you need to use temtable after sp execution then use ## rather than # then we can access it or we can use persistent temporary table
Please make sure that your query statements is correctly.
Try this in your stored procedure and check the output results ( copy the result and execute it)
....
SET #FinalQuery='SELECT '+#Query+' '+#Where+'
PRINT(#FinalQuery)
....
You can use the SQL Profiler tool to debug
Try this...
First create the temp table which you need for further calculation.
CREATE TABLE #TEMP
(
STATEID INT,
DEPTID INT
)
DECLARE #STATEID CHAR(10)='STATEID';
DECLARE #DEPTID CHAR(15)='DEPTID';
DECLARE #QUERY VARCHAR(MAX)='INSERT INTO #TEMP_TABLE
SELECT COLUMNS WITH JOINS PASSED FROM FRONT END'
DECLARE #WHERE VARCHAR(500);
DECLARE #FINALQUERY VARCHAR(MAX)=''
SET #WHERE='SOME WHERE CONDITION'
SET #FINALQUERY=+#QUERY+' '+#WHERE+'' -- REMOVED SELECT
EXEC(#FINALQUERY)

Run SQL pre-defined function stored in table

I have a table which stores a SQL predefined function, like CONVERT(VARCHAR(10), '2012-08-21 00:16:41.993', 101) in a row/column. While retrieving the result from table, it should run the function and give the final outcome as "2012-08-21", instead right now it returns the same function statement. I am running select (select RunDate from RunDate) and using SQL server database.
Kindly help!!
You need to use dynamic SQL for this. You can't just nest expressions and have SQL evaluate the output...
DECLARE #x TABLE(sql NVARCHAR(255));
INSERT #x(sql) SELECT N'CONVERT(VARCHAR(10), ''2012-08-21 00:16:41.993'', 101)';
DECLARE #sql NVARCHAR(MAX);
SELECT #sql = N'SELECT ' + sql FROM #x;
EXEC sp_executesql #sql;
It would look like this (adjust accordingly):
DECLARE #predef VARCHAR(1000);
DECLARE #sqlquery VARCHAR(1000);
SELECT #predef = (SELECT top 1 Value FROM Parameters Where Name = 'MYFUNC');
SET #sqlquery = 'select ' + #predef + ' from SomeTable';
EXECUTE ( #sqlquery );
One tip: here be dragons. Beware of SQL Injection.

using dynamic IN clause in MSSQL

Why the following SQL does not fetch me anything
DECLARE #Status AS VARCHAR(400)
SET #status = '''Closed'',''OPEN'''
select * from MYTABLE where status in(#status)
While as
select * from MYTABLE where status in('Closed','Open') fetches me rows
You can if you want do some dynamic SQL but I think it is not really competitive..
DECLARE #Status nVARCHAR(400),
#SQL nvarchar(500)
SET #status = '''Closed'''+','+'''OPEN'''
set #SQL = '
select * from [MYTABLE] where status in('+#status +')'
exec sp_executesql #SQL
GO
Your first question checks if the value 'Closed','OPEN' exists in the database. The values is not expanded.
If you use SQL Server 2008 or later you can use Table Valued Parameters to achieve the same thing.