Alias in SQL Server - sql-server

select eomonth('2023-01-01')
I want my alias to be picked by the function MONTHNAME('2023-01-01') so my output would be 2023-01-30 and my alias would be January

You can use DATENAME:
select eomonth('2023-01-01') ,DATENAME(MONTH, eomonth('2023-01-01') )
Dynamic alias:
declare #yourdate date = '2023-01-01'
declare #monthname nvarchar(20)=(select DATENAME(MONTH,#yourdate))
declare #SQL nvarchar(200) = concat('select eomonth(',quotename(#yourdate,char(39)),') as ',#monthname )
exec sp_executesql #SQL
Add your query:
declare #yourdate date = '2023-01-01'
declare #monthname nvarchar(20)=(select DATENAME(MONTH,#yourdate))
declare #anothersql nvarchar(500) = ',COALESCE((SELECT SUM(deductdays) FROM tbl_LeaveDeduction WHERE CHARINDEX(quotename(CAST(EmpId AS varchar(10)),char(44)), #EmpIds) > 0 and DATEPART(MONTH,DeductionDate)= DATEPART(MONTH,#StartofYear) ),0)'
declare #SQL nvarchar(500) = concat('select eomonth(',quotename(#yourdate,char(39)),') as ',#monthname,#anothersql )
exec sp_executesql #SQL

Related

How to store Exec result to datetime variable where exec result has variable table name?

How can I store my execution result in datetime variable?
My query look like this:
Declare #F VARCHAR(50) = (select replace ('H-10','-',''));
DECLARE #SQLQuery AS NVARCHAR(500)
set #SQLQuery=
N'SELECT
top 1 DATEADD(MINUTE, -330, time_stamp) as time
FROM
DMD_'+#F+'_DC_data
ORDER BY
time_stamp ASC';
DECLARE #SOR_time datetime
set #SOR_time=Exec (#SQLQuery)
If you want to store the ... execution result in datetime variable..., one solution is to execute the generated statement using sp_executesql with an OUTPUT parameter:
DECLARE #F varchar(50) = (select replace ('H-10', '-', ''));
DECLARE #SOR_time datetime
DECLARE #SQLQuery AS nvarchar(500)
SET #SQLQuery =
N'SELECT TOP 1 #SOR_time = DATEADD(MINUTE, -330, time_stamp) ' +
N'FROM QUOTE_NAME(DMD_' + #F + '_DC_data) ' +
N'ORDER BY time_stamp ASC'
;
DECLARE #rc int
EXEC #rc = sp_executesql
#SQLQuery,
N'#SOR_time datetime OUTPUT',
#SOR_time OUTPUT
IF #rc <> 0 PRINT 'Error'
Try following way. Execute query result store into the table instead of assign to a variable.
Declare #F VARCHAR(50) = (select replace ('H-10','-',''));
DECLARE #SQLQuery AS NVARCHAR(500)
set #SQLQuery=
N'SELECT
top 1 DATEADD(MINUTE, -330, time_stamp) as time
FROM
DMD_'+#F+'_DC_data
ORDER BY
time_stamp ASC';
DECLARE #TempTable TABLE (SOR_time datetime)
insert #TempTable
exec (#SQLQuery)
select * from #TempTable
You can just assign to variable inside query if result set is just a single variable
Declare #F VARCHAR(50) = (select replace ('H-10','-',''));
DECLARE #SQLQuery AS NVARCHAR(500)
DECLARE #SOR_time DATETIME
set #SQLQuery=
N'SELECT
top 1 #SOR_time = DATEADD(MINUTE, -330, time_stamp)
FROM
DMD_'+#F+'_DC_data
ORDER BY
time_stamp ASC';
-- PRINT #SQLQuery
Exec (#SQLQuery)
SELECT #SOR_time

Execute SQL with "SELECT #daynamic_variable_name" in SQL SERVER

Through the exec in SQL Server, I want to retrieve the parameter's value dynamically. Please look into the below Example:
declare #p1 varchar(50) = '10'
declare #p2 varchar(50) = '20'
declare #p_nm varchar(50)
set #p_nm = '#p1' -- OR set #p_nm = '#p2'
declare #sql varchar(50) = 'select #p1'
declare #ans_val varchar(50)
set #ans_val = exec #sql
How could I get the result 10 if using set #p_nm = '#p1' and 20 if using set #p_nm = '#p2'?
In my case set #ans_val = exec #sql giving syntax error.
A variable only has scope within the batch it is inside. When you run dynamic SQL, the dynamic SQL has a different scope, so variables cannot be accessed if they are in a different one. For example, both of the following statements will generate an error:
DECLARE #SQL nvarchar(MAX) = N'SELECT #i;';
DECLARE #i int = 1;
EXEC (#SQL);
GO
DECLARE #SQL nvarchar(MAX) = N'DECLARE #i int = 1;';
EXEC (#SQL);
SELECT #i;
GO
If you are running dynamic SQL, you need to pass details of any variables as parameters, using sp_executesql. For example:
DECLARE #SQL nvarchar(MAX) = N'SELECT #n;';
DECLARE #i int = 1;
EXEC sp_executesql #SQL, N'#n int', #n = #i;
If you want the return scalar values to a variable, use an OUTPUT parameter (personally, I recommend against the syntax {Variable} = EXEC {Expression/Stored Procedure}, one reason being you are therefore limited to one scalar value).
So, again, as an example:
DECLARE #SQL nvarchar(MAX) = N'SET #a = #n + 1;';
DECLARE #i int = 1, #b int;
EXEC sp_executesql #SQL, N'#n int, #a int OUTPUT', #n = #i, #a = #b OUTPUT;
PRINT #b;
I'll do it like:
EXECUTE sp_executesql
N'SELECT #Var AS Result',
N'#Var VARCHAR(5)',
#Var = '12345';
Results:
+----+--------+
| | Result |
+----+--------+
| 1 | 12345 |
+----+--------+
Or
DECLARE #Out VARCHAR(5);
EXECUTE sp_executesql
N'SELECT #Out = #Var',
N'#Var VARCHAR(5) , #Out VARCHAR(5) OUTPUT',
#Var = '12345',
#Out = #Out OUTPUT;
SELECT #Out As Result;
Finally, please don't forgot to visit sp_executesql

How can I use a local variable in SELECT FROM?

I declared a variable #Obj and assign a complete table name 'ODS..Account' to it.
DECLARE #Obj VARCHAR(255)
Then I used it in a query immediately after FROM Clause. I perceive it is just a string, unable to act as a table object. So how can I fix the code to get it works? Cheers
INSERT Control.dbo.Consistency_Check
(Table_Name
,Schema_Name
,Id
,Incremental_DateTime_Column
)
SELECT
#Tab
,'ODS'
,Id
,SystemModstamp
FROM
#Obj )
You can use a local variable as a scalar value, not as a function. To do this, you need dynamic SQL:
declare #sql varchar(max);
select #sql = '
INSERT Control.dbo.Consistency_Check(Table_Name, Schema_Name, Id, Incremental_DateTime_Column)
SELECT ''#Tab'', 'ODS', Id, SystemModstamp
FROM #Tab
';
select #sql = replace(#sql, '#tab', #tab);
exec sp_executesql #sql;
Slightly different way of doing it with dynamic SQL:
DECLARE #Obj VARCHAR(255) = 'dbo.table'
DECLARE #SQL NVARCHAR(MAX) = ''
SET #SQL = #SQL +
'INSERT Control.dbo.Consistency_Check
(Table_Name
,Schema_Name
,Id
,Incremental_DateTime_Column
)
SELECT
#Tab
,''ODS''
,Id
,SystemModstamp
FROM
' + #Obj + ''
EXEC (#SQL)
You cannot. You probably want to use dynamic query. i.e. workout the SQL query string into a variable and exec using sp_executesql.
You may use the same variable name in the dynamic SQL but I changed it to #p_Tab for the example.
DECLARE #Tab int = 3
DECLARE #SQLString nvarchar(500)
DECLARE #ParmDefinition nvarchar(500) = N'#p_Tab int';
Declare #TableName nvarchar(100) = 'ODS..Account'
/* Build the SQL string dynamicly.*/
SET #SQLString = N'INSERT Control.dbo.Consistency_Check
(Table_Name
,Schema_Name
,Id
,Incremental_DateTime_Column
)
SELECT
#p_Tab
,''ODS''
,Id
,SystemModstamp
FROM
'+ #TableName
EXECUTE sp_executesql #SQLString, #ParmDefinition,
#p_Tab = #Tab
Further reference: https://msdn.microsoft.com/en-us/library/ms188001.aspx

EXEC sp_executesql with multiple parameters

How to pass the parameters to the EXEC sp_executesql statement correctly?
This is what I have now, but i'm getting errors:
alter PROCEDURE [dbo].[usp_getReceivedCases]
-- Add the parameters for the stored procedure here
#LabID int,
#RequestTypeID varchar(max),
#BeginDate date,
#EndDate date
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
declare #statement nvarchar(4000)
set #statement = N'select SentToLab,
FROM dbo.vEmailSent
WHERE SentToLab_ID=#LabID and convert(date,DateSent) >= #BeginDate
and CONVERT(date, datesent) <= #EndDate
and RequestType_ID in ( #RequestTypeID )
EXEC sp_executesql #statement,N'#LabID int', #LabID, N'#BeginDate date', #BeginDate,N'#EndDate date', #EndDate, #RequestTypeID=#RequestTypeID
END
RequestTypeID is a comma delimited list of integers, like so: "1,2,3,4,5"
here is my try #2, also unsuccessful
declare #statement nvarchar(4000)
SET #statement =' select SentToLab_ID
FROM dbo.vEmailSent
WHERE
SentToLab_ID='+#LabID+' and convert(date,DateSent) >= '+#BeginDate +'
and CONVERT(date, datesent) <= '+#EndDate+'
and RequestType_ID in ('+ #RequestTypeID+' )
group by FileStream_ID, SentToLab_ID'
EXEC(#statement)
Operand type clash: date is incompatible with int
Here is a simple example:
EXEC sp_executesql #sql, N'#p1 INT, #p2 INT, #p3 INT', #p1, #p2, #p3;
Your call will be something like this
EXEC sp_executesql #statement, N'#LabID int, #BeginDate date, #EndDate date, #RequestTypeID varchar', #LabID, #BeginDate, #EndDate, #RequestTypeID
This also works....sometimes you may want to construct the definition of the parameters outside of the actual EXEC call.
DECLARE #Parmdef nvarchar (500)
DECLARE #SQL nvarchar (max)
DECLARE #xTxt1 nvarchar (100) = 'test1'
DECLARE #xTxt2 nvarchar (500) = 'test2'
SET #parmdef = '#text1 nvarchar (100), #text2 nvarchar (500)'
SET #SQL = 'PRINT #text1 + '' '' + #text2'
EXEC sp_executeSQL #SQL, #Parmdef, #xTxt1, #xTxt2
If one need to use the sp_executesql with OUTPUT variables:
EXEC sp_executesql #sql
,N'#p0 INT'
,N'#p1 INT OUTPUT'
,N'#p2 VARCHAR(12) OUTPUT'
,#p0
,#p1 OUTPUT
,#p2 OUTPUT;
maybe this help :
declare
#statement AS NVARCHAR(MAX)
,#text1 varchar(50)='hello'
,#text2 varchar(50)='world'
set #statement = '
select '''+#text1+''' + '' beautifull '' + ''' + #text2 + '''
'
exec sp_executesql #statement;
this is same as below :
select #text1 + ' beautifull ' + #text2

How to get value for Temp variable in Sql?

I write a query in sql server i am getting value in a temporary variable, this is my query
declare #tacolumn1 varchar(50)='cargo'
declare #temp1 varchar(50)
declare #sql nvarchar(max)
print #tacolumn1
set #sql= ('select '+#tacolumn1+' from operatingincome where YEAR(createddate)= 2009')
exec sp_executesql #sql
print #temp1
from the above #sql has the value , now i want to save that value in #temp1 how can i do that one
sp_executesql procedure can have input and output parameters:
DECLARE #IntVariable int;
DECLARE #SQLString nvarchar(500);
DECLARE #ParmDefinition nvarchar(500);
DECLARE #max_title varchar(30);
SET #IntVariable = 197;
SET #SQLString = N'SELECT #max_titleOUT = max(JobTitle)
FROM AdventureWorks2008R2.HumanResources.Employee
WHERE BusinessEntityID = #level';
SET #ParmDefinition = N'#level tinyint, #max_titleOUT varchar(30) OUTPUT';
EXECUTE sp_executesql #SQLString, #ParmDefinition, #level = #IntVariable, #max_titleOUT=#max_title OUTPUT;
SELECT #max_title;

Resources